How to keep get notification using awesome package after app is terminated in Flutter?

137

I guess you are using firebase_messaging with your app. To handle message when the app is terminated/background state, you have to create a firebase background message handler:

Above main() in main.dart

import ....

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  print('Handling a background message ${message.messageId}');
  // await Firebase.initializeApp();
  print('Handling a background message ${message.messageId}');
  await AwesomeNotifications().createNotification(
          content: NotificationContent(
            id: message.hashCode,
            channelKey: "high_importance_channel",
            title: message.data['title'],
            body: message.data['body'],
            bigPicture: message.data['image'],
            notificationLayout: NotificationLayout.BigPicture,
            largeIcon: message.data['image'],
            payload: Map<String, String>.from(message.data),
            hideLargeIconOnExpand: true,
          ),
        );
}

This will create a Background service ( isolate ) that will listen to notifications when the app is terminated ( removed from recents ) or in background ( in recents )

In main()

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  AwesomeNotifications().initialize(
    null,
    [
      NotificationChannel(
          channelKey: 'high_importance_channel',
          channelName: 'high_importance_channel',
          channelDescription: 'High_importance_channel',
          ledColor: Colors.white,
          defaultColor: Colors.white,
          enableVibration: true,
          playSound: true,
          enableLights: true,
          importance: NotificationImportance.High,
      );
    ],
  );
  AwesomeNotifications().actionStream.listen((event) {
    print(event.payload!);
  });
  runApp(MyApp());
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);
}

Here we did create a Notification channel and initialized the awesome_notification plugin. So, all the notification will be recieved on this channel.

You can further use this channel to show foreground notifications too.

Note:

No app delivers notification when the app is forced stop from settings

Share:
137
Abdelrahman Bahig
Author by

Abdelrahman Bahig

Updated on December 01, 2022

Comments

  • Abdelrahman Bahig
    Abdelrahman Bahig over 1 year

    I am using awesome package for notification i want to know how to keep get notification while app is terminated.