Bird
Raised Fist0
Fluttermobile~20 mins

Notifications (local) in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Local Notification Demo
This screen shows a button that, when tapped, triggers a local notification on the device.
Target UI
-------------------------
| Local Notification Demo |
|-----------------------|
|                       |
|   [ Show Notification ]|
|                       |
-------------------------
Add a button labeled 'Show Notification' centered on the screen.
When the button is tapped, display a local notification with a title and message.
Use flutter_local_notifications package for notification handling.
Request notification permissions if needed.
Ensure the notification appears even if the app is in the background.
Starter Code
Flutter
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: NotificationScreen(),
    );
  }
}

class NotificationScreen extends StatefulWidget {
  const NotificationScreen({super.key});

  @override
  State<NotificationScreen> createState() => _NotificationScreenState();
}

class _NotificationScreenState extends State<NotificationScreen> {
  // TODO: Initialize notification plugin here

  @override
  void initState() {
    super.initState();
    // TODO: Request permissions and initialize notifications
  }

  void _showNotification() {
    // TODO: Show a local notification
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Local Notification Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _showNotification,
          child: const Text('Show Notification'),
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
Flutter
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: NotificationScreen(),
    );
  }
}

class NotificationScreen extends StatefulWidget {
  const NotificationScreen({super.key});

  @override
  State<NotificationScreen> createState() => _NotificationScreenState();
}

class _NotificationScreenState extends State<NotificationScreen> {
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  @override
  void initState() {
    super.initState();
    _initializeNotifications();
  }

  Future<void> _initializeNotifications() async {
    const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher');
    const DarwinInitializationSettings initializationSettingsIOS = DarwinInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
    );
    const InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );

    await flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  Future<void> _showNotification() async {
    const AndroidNotificationDetails androidDetails = AndroidNotificationDetails(
      'channel_id',
      'Local Notifications',
      channelDescription: 'Channel for local notifications',
      importance: Importance.max,
      priority: Priority.high,
      ticker: 'ticker',
    );
    const DarwinNotificationDetails iosDetails = DarwinNotificationDetails();
    const NotificationDetails platformDetails = NotificationDetails(
      android: androidDetails,
      iOS: iosDetails,
    );

    await flutterLocalNotificationsPlugin.show(
      0,
      'Hello!',
      'This is a local notification.',
      platformDetails,
      payload: 'Notification Payload',
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Local Notification Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _showNotification,
          child: const Text('Show Notification'),
        ),
      ),
    );
  }
}

We use the flutter_local_notifications package to handle local notifications.

In initState, we initialize the notification plugin with settings for Android and iOS, requesting permissions on iOS.

The _showNotification method creates notification details for both platforms and calls show to display the notification immediately.

The button triggers this method when tapped, so the user sees a notification with a title and message.

Final Result
Completed Screen
-------------------------
| Local Notification Demo |
|-----------------------|
|                       |
|   [ Show Notification ]|
|                       |
-------------------------
User taps 'Show Notification' button.
A local notification appears on the device with title 'Hello!' and message 'This is a local notification.'.
Notification shows even if app is in background.
Stretch Goal
Add a notification action button that opens the app when tapped.
💡 Hint
Use the 'payload' parameter in show() and handle it in onSelectNotification callback during initialization.

Practice

(1/5)
1. What is the main purpose of local notifications in a Flutter app?
easy
A. To alert users even when the app is closed or in the background
B. To send messages to a server
C. To update the app's UI instantly
D. To change app theme colors automatically

Solution

  1. Step 1: Understand local notifications

    Local notifications are alerts shown to users even if the app is not open or running in the background.
  2. Step 2: Compare options

    Options B, C, and D describe other app features unrelated to local notifications.
  3. Final Answer:

    To alert users even when the app is closed or in the background -> Option A
  4. Quick Check:

    Local notifications alert users outside app use = A [OK]
Hint: Local notifications work when app is not active [OK]
Common Mistakes:
  • Confusing local notifications with server messages
  • Thinking notifications only work when app is open
  • Mixing UI updates with notification purpose
2. Which Flutter plugin is commonly used to show local notifications?
easy
A. firebase_messaging
B. flutter_local_notifications
C. provider
D. http

Solution

  1. Step 1: Identify notification plugins

    The plugin flutter_local_notifications is designed for local notifications in Flutter apps.
  2. Step 2: Eliminate unrelated plugins

    http is for network calls, provider for state management, firebase_messaging for push notifications, not local.
  3. Final Answer:

    flutter_local_notifications -> Option B
  4. Quick Check:

    Local notifications plugin = flutter_local_notifications [OK]
Hint: Local notifications use flutter_local_notifications plugin [OK]
Common Mistakes:
  • Choosing firebase_messaging which is for push, not local
  • Confusing state management plugins with notification plugins
  • Selecting network plugins by mistake
3. What will happen if you call show() on a local notification without initializing the plugin first?
medium
A. The notification will show normally
B. The notification will show only on Android devices
C. The notification will be delayed by 5 seconds
D. The app will crash or throw an error

Solution

  1. Step 1: Understand plugin initialization

    Local notification plugins require initialization before use to set up channels and permissions.
  2. Step 2: Consequence of missing initialization

    Calling show() without initialization causes runtime errors or crashes because the plugin is not ready.
  3. Final Answer:

    The app will crash or throw an error -> Option D
  4. Quick Check:

    Uninitialized plugin causes error/crash = B [OK]
Hint: Always initialize plugin before showing notifications [OK]
Common Mistakes:
  • Assuming notifications show without initialization
  • Thinking notifications delay automatically
  • Believing platform-specific behavior without init
4. Given this code snippet, what is the error?
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Missing initialization here
  await flutterLocalNotificationsPlugin.show(
    0,
    'Hello',
    'Welcome to Flutter',
    NotificationDetails(
      android: AndroidNotificationDetails('channelId', 'channelName')
    )
  );
}
medium
A. WidgetsFlutterBinding.ensureInitialized() is unnecessary
B. NotificationDetails is not imported
C. Missing call to initialize() before show()
D. Notification ID cannot be zero

Solution

  1. Step 1: Check plugin initialization

    The code calls show() without calling initialize() on flutterLocalNotificationsPlugin first.
  2. Step 2: Understand consequences

    Without initialize(), the plugin is not ready, causing errors when showing notifications.
  3. Final Answer:

    Missing call to initialize() before show() -> Option C
  4. Quick Check:

    Initialize plugin before show() = C [OK]
Hint: Always initialize plugin before calling show() [OK]
Common Mistakes:
  • Ignoring the need to initialize plugin
  • Thinking zero ID is invalid
  • Assuming ensureInitialized() replaces plugin init
5. You want to create a local notification channel with high importance and priority on Android. Which code snippet correctly sets this up?
hard
A. AndroidNotificationDetails('channelId', 'channelName', importance: Importance.high, priority: Priority.high)
B. AndroidNotificationDetails('channelId', 'channelName', importance: Importance.low, priority: Priority.min)
C. AndroidNotificationDetails('channelId', 'channelName', importance: Importance.defaultImportance, priority: Priority.defaultPriority)
D. AndroidNotificationDetails('channelId', 'channelName')

Solution

  1. Step 1: Understand importance and priority

    High importance and priority make notifications more visible and urgent on Android.
  2. Step 2: Check code options

    AndroidNotificationDetails('channelId', 'channelName', importance: Importance.high, priority: Priority.high) sets importance and priority to high, matching the requirement. Others set low, default, or omit these settings.
  3. Final Answer:

    AndroidNotificationDetails('channelId', 'channelName', importance: Importance.high, priority: Priority.high) -> Option A
  4. Quick Check:

    High importance and priority = AndroidNotificationDetails('channelId', 'channelName', importance: Importance.high, priority: Priority.high) [OK]
Hint: Use Importance.high and Priority.high for urgent notifications [OK]
Common Mistakes:
  • Leaving importance and priority at default
  • Using low importance for urgent alerts
  • Omitting priority setting
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard