How to handle notification action button clicks in background in Flutter using awesome_notifications?

2.7k Views Asked by At

I am using awesome notifications in Flutter to show local notifications. My plan is to have an action button in a notification, which changes some values in the shared preferences in the background (without opening the app) when pressed. Is this even possible to do?

I tried using onActionReceivedMethod-listener and getInitialNotificationAction-method in my main function after initializing awesome notifications:

AwesomeNotifications().setListeners(onActionReceivedMethod: (action) async{
  print(action.body);
});

// OR

ReceivedAction? receivedAction = await AwesomeNotifications().getInitialNotificationAction(
    removeFromActionEvents: false
);
if (receivedAction?.body != null){
  print(receivedAction.body);
}

Both of them worked (separetly used) only when the app had already started, but they also gave this error:

Awesome Notifications: A background message could not be handled in Dart because there is no dart background handler registered. (BackgroundService:58)

But how I could get it working when the app is not opened? Can I create a backgroung handler without Firebase, or is there some other way to achieve this?

Here is my code, how I create the notification:

static Future<void> createSimpleNotification() async {
  await AwesomeNotifications().createNotification(
    content: NotificationContent(
        id: 1,
        channelKey: 'important_channel',
        title: 'Title',
        body: 'Test',
        largeIcon: 'asset://assets/iconPhoto.png'),
    actionButtons: [
      NotificationActionButton(
          key:'key',
          label: 'label',
          actionType: ActionType.SilentBackgroundAction)]
  );
}
1

There are 1 best solutions below

2
On BEST ANSWER

I found the answer from here: Cannot find AwesomeNotifications().actionStream

I implemented it like this:

@pragma("vm:entry-point")
Future<void> _onActionReceivedMethod(ReceivedAction action) async {
  print('It works');
}

And it worked both when the app was in the background or in the foreground.