flutterdartbuttonnotificationsflutter-local-notification

How to handle notification actions with flutter_local_notification package?


I have added 2 buttons to my notification in the code below But I don't know how to find out which button is pressed and do something based on that

  Future<void> zonedScheduleAlarmClockNotification({
    required Duration duration,
    required String title,
    required String message,
    required String type,
  }) async {
    print(duration);
    final random = Random();
    int id = random.nextInt(999999999);
    await flutterLocalNotificationsPlugin.zonedSchedule(
      id,
      title,
      message,
      tz.TZDateTime.now(tz.local).add(duration),
      
      NotificationDetails(
        android: AndroidNotificationDetails(
          'alarm_clock_channel',
          'Alarm Clock Channel',
          channelDescription: 'Alarm Clock Notification',
          subText: type,
          //silent: true,
          color: Colors.amber,
          colorized: true,
          ticker: title,
          playSound: true,
          priority: Priority.high,
          importance: Importance.high,
          
          actions: <AndroidNotificationAction>[
            const AndroidNotificationAction(
              'id_2',
              'Completed',
              titleColor: Color.fromARGB(255, 255, 0, 0),
              icon: DrawableResourceAndroidBitmap('secondary_icon'),
            ),
             const AndroidNotificationAction(
              's',
              'Action 3',
              icon: DrawableResourceAndroidBitmap('secondary_icon'),
              showsUserInterface: true,
              // By default, Android plugin will dismiss the notification when the
              // user tapped on a action (this mimics the behavior on iOS).
              cancelNotification: false,
            ), 
          ],
        ),
      ),
      androidScheduleMode: AndroidScheduleMode.alarmClock,
      payload: title,
      uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
    );
  }

I wanted the user to perform tasks within the app on each of the buttons he pressed But I can't figure out how to find out which button the user clicked and when


Solution

  • As you could see in the document, it needs some configuration for iOS, but then, if you have done that, or you are on android, it is said that you should declare a top level function to receive the notification in the app and act on it. There you could check the actionId of notificationResponse and act accordingly.

    For instance, in your project here you could write something like:

    @pragma('vm:entry-point')
    void notificationTapBackground(NotificationResponse notificationResponse) {
      if (notificationResponse.actionId == 'id_2') {
        // do something
      } else if (notificationResponse.actionId == 's') {
        // do something else
      }
    }