Search code examples
flutterflutter-local-notification

How to add Scheduled notification in flutter


I have been trying to add a scheduled notification feature to my todo app but am unable to do so, when the notification is supposed to appear, it does not and the app crashes, I want the notification to be added when the add button in the todoScreen is clicked. any help would be really appreciated.

todoScreen link: https://github.com/Rohith-JN/Reminders_App/blob/main/lib/Screens/TodoScreen.dart

notification link: https://github.com/Rohith-JN/Reminders_App/blob/main/lib/notification_service.dart


Solution

  • Okay pushing notification with flutter is pretty easy. Add these dependencies to pubspec.yaml:

    dependencies:
      flutter_local_notifications: ^1.4.2
      rxdart: ^0.23.1
    

    Particular plugins: flutter_local_notifications and rxdart

    then run this command in the terminal:

    flutter pub get
    

    Go to AndroidManifest.xml in /android/app/src/main/ and add these lines:

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    

    Now, go to AppDelegate.swift in /ios/Runner/ Add:

    if #available(iOS 10.0, *) {
    UNUserNotificationCenter.current().delegate = self as ? 
    UNUserNotificationCenterDelegate    
    }
    

    before these lines:

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    

    Done?

    Now, Create a notifications_helper.dart file and import the flutter_local_notifications and rxdart packages. Then in that file add these:

    class NotificationClass{
      final int id;
      final String title;
      final String body;
      final String payload;
    NotificationClass({this.id, this.body, this.payload, this.title});
    }
    

    Also add these finals:

    final rxSub.BehaviorSubject<NotificationClass> didReceiveLocalNotificationSubject =
        rxSub.BehaviorSubject<NotificationClass>();
    final rxSub.BehaviorSubject<String> selectNotificationSubject =
        rxSub.BehaviorSubject<String>();
    

    Now finally add the following method to helper file:

    Future<void> initNotifications(
        notifs.FlutterLocalNotificationsPlugin
            notifsPlugin) async {
      var initializationSettingsAndroid =
          notifs.AndroidInitializationSettings('icon');
      var initializationSettingsIOS = notifs.IOSInitializationSettings(
          requestAlertPermission: false,
          requestBadgePermission: false,
          requestSoundPermission: false,
          onDidReceiveLocalNotification:
              (int id, String title, String body, String payload) async {
            didReceiveLocalNotificationSubject
                .add(NotificationClass(id: id, title: title, body: body, payload: payload));
          });
      var initializationSettings = notifs.InitializationSettings(
          initializationSettingsAndroid, initializationSettingsIOS);
      await notifsPlugin.initialize(initializationSettings,
          onSelectNotification: (String payload) async {
        if (payload != null) {
          print('notification payload: ' + payload);
        }
        selectNotificationSubject.add(payload);
      });
      print("Notifications initialised successfully");
    }
    

    For permission request method for iOS:

    void requestIOSPermissions(
        notifs.FlutterLocalNotificationsPlugin notifsPlugin) {
      notifsPlugin.resolvePlatformSpecificImplementation<notifs.IOSFlutterLocalNotificationsPlugin>()
          ?.requestPermissions(
            alert: true,
            badge: true,
            sound: true,
          );
    }
    

    Done Up To This?

    Now, scheduled notification, add these:

    Future<void> scheduleNotification(
        {notifs.FlutterLocalNotificationsPlugin notifsPlugin,
        String id,
        String title,
        String body,
        DateTime scheduledTime}) async {
      var androidSpecifics = notifs.AndroidNotificationDetails(
        id, // This specifies the ID of the Notification
        'Scheduled notification', // This specifies the name of the notification channel
        'A scheduled notification', //This specifies the description of the channel
        icon: 'icon',
      );
      var iOSSpecifics = notifs.IOSNotificationDetails();
      var platformChannelSpecifics = notifs.NotificationDetails(
          androidSpecifics, iOSSpecifics);
      await notifsPlugin.schedule(0, title, "Scheduled notification",
          scheduledTime, platformChannelSpecifics); // This literally schedules the notification
    }
    

    Now modify the main.dart file:

    NotificationAppLaunchDetails notifLaunch;
    final FlutterLocalNotificationsPlugin notifsPlugin=    
    FlutterLocalNotificationsPlugin();
    

    Now within the main method, add

    notifLaunch = await notifsPlugin.getNotificationAppLaunchDetails();
    await initNotifications(notifsPlugin);
    requestIOSPermissions(notifsPlugin);
    

    NOW MAIN THING, Triggering a scheduled Notification, Import your helper file and main.dart:

    import '../helpers/notifications_helper.dart';
    import '../main.dart';
    

    Now call the scheduleNotification method:

    scheduleNotification(
        notifsPlugin: notifsPlugin, //Or whatever you've named it in main.dart
        id: DateTime.now().toString(),
        body: "A scheduled Notification",
        scheduledTime: DateTime.now()); //Or whenever you actually want to trigger it
    

    And My friend you are done!👍