flutter_local_notifications

repository·master·Indexed 25 days ago

https://github.com/maikub/flutter_local_notifications

A cross-platform Flutter plugin for displaying local notifications on Android, iOS, macOS, Linux, Windows, and Web. It supports basic notifications, scheduling, periodic alerts, and platform-specific features such as Android notification channels, iOS attachments, and Windows toast notifications. Requires Flutter SDK 3.38.1 or newer.

Tokens
15.4K
Snippets
31
Records
68
Agent score
81%

What's inside flutter_local_notifications

  1. Use the flutter_local_notifications plugin

    master

    The flutter_local_notifications package is the primary cross-platform plugin used to display local notifications within Flutter applications. While the repository contains multiple packages for specific platform implementations (Linux, Windows, Web), most developers should interact directly with the main flutter_local_notifications package.

    For detailed setup instructions, platform-specific configurations, and feature-specific code samples, refer to the README file located within the flutter_local_notifications directory or check the provided example app.

  2. Schedule a zoned notification

    master

    To avoid issues with Daylight Saving Time, use zonedSchedule instead of the deprecated schedule method. This requires the timezone package.

    Steps:

    1. Add timezone as a direct dependency.
    2. Initialize the timezone database with tz.initializeTimeZones().
    3. Set the local location using tz.setLocalLocation().
    4. Use tz.TZDateTime to define the scheduled time.

    On Android, use androidScheduleMode to control precision. AndroidScheduleMode.exactAllowWhileIdle allows exact timing even in low-power modes, but requires the 'exact alarm' permission.

    import 'package:timezone/data/latest_all.dart' as tz;
    import 'package:timezone/timezone.dart' as tz;
    
    // Initialize
    tz.initializeTimeZones();
    tz.setLocalLocation(tz.getLocation(timeZoneName));
    
    // Schedule
    await flutterLocalNotificationsPlugin.zonedSchedule(
        0,
        title: 'scheduled title',
        body: 'scheduled body',
        scheduledDate: tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
        const NotificationDetails(
            android: AndroidNotificationDetails(
                'your channel id', 'your channel name',
                channelDescription: 'your channel description')),
        androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle);
  3. Build and bundle native Windows code manually

    master

    The native C++ code in the src directory can be built using CMake to generate a DLL. This is primarily useful for local testing outside of the Flutter environment. When developing a standard Flutter app, Flutter handles the building and bundling of these assets automatically.

    To build manually, use the provided build.bat script or the following commands:

    @echo off
    cd build
    cmake ../windows
    cmake --build .
    cd ..
    copy build\shared\Debug\flutter_local_notifications_windows.dll .
  4. Configure Notification Icons and Sounds for Android

    master

    Notification icons should be added as drawable resources. Custom sounds should be added as raw resources.

    When using AndroidNotificationDetails:

    • Use DrawableResourceAndroidBitmap to load an icon from a drawable resource.
    • Use FilePathAndroidBitmap to load an icon from a file path.

    Important: For Android 8.0+, sounds and vibrations are tied to the notification channel. These settings can only be configured when the channel is first created. Subsequent notifications using the same channel ID cannot change these properties.

  5. Request notification permissions on iOS and macOS

    master

    To avoid showing permission prompts immediately upon app launch, initialize the plugin with permission request flags set to false. You can then call requestPermissions at a more appropriate time in your application flow using resolvePlatformSpecificImplementation.

    // 1. Initialize with permissions set to false
    final DarwinInitializationSettings initializationSettingsDarwin =
        DarwinInitializationSettings(
        requestSoundPermission: false,
        requestBadgePermission: false,
        requestAlertPermission: false,
      );
    
    // ... initialize plugin ...
    
    // 2. Request permissions later
    final bool result = await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
        ?.requestPermissions(
        alert: true,
        badge: true,
        sound: true,
        );
  6. Initialize Flutter Local Notifications

    master

    To use the plugin, create an instance of FlutterLocalNotificationsPlugin and initialize it with platform-specific settings. You must provide settings for the platforms you target, or you will encounter a runtime ArgumentError.

    Key components:

    • AndroidInitializationSettings: Requires an icon name that must exist as a drawable resource in your Android project.
    • DarwinInitializationSettings: Used for iOS and macOS.
    • LinuxInitializationSettings: Requires a defaultActionName.
    • WindowsInitializationSettings: Requires appName, appUserModelId, and a guid.
    • onDidReceiveNotificationResponse: An optional callback triggered when a notification is tapped while the app is running. Note that this callback cannot be used to handle cases where the notification launched the app; use getNotificationAppLaunchDetails for that purpose.
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        FlutterLocalNotificationsPlugin();
    
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('app_icon');
    final DarwinInitializationSettings initializationSettingsDarwin =
        DarwinInitializationSettings();
    final LinuxInitializationSettings initializationSettingsLinux =
        LinuxInitializationSettings(
            defaultActionName: 'Open notification');
    final WindowsInitializationSettings initializationSettingsWindows =
        WindowsInitializationSettings(
            appName: 'Flutter Local Notifications Example',
            appUserModelId: 'Com.Dexterous.FlutterLocalNotificationsExample',
            guid: 'd49b0314-ee7a-4626-bf79-97cdb8a991bb')
    final InitializationSettings initializationSettings = InitializationSettings(
        android: initializationSettingsAndroid,
        iOS: initializationSettingsDarwin,
        macOS: initializationSettingsDarwin,
        linux: initializationSettingsLinux,
        windows: initializationSettingsWindows);
    
    await flutterLocalNotificationsPlugin.initialize(
        settings: initializationSettings,
        onDidReceiveNotificationResponse: onDidReceiveNotificationResponse);