Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To display a local notification when a Firebase notification is received in both the foreground and background in Flutter, you need to handle the incoming notification in both scenarios.

First, you need to configure your app to handle Firebase notifications by registering your app with Firebase Cloud Messaging (FCM) and configuring the necessary dependencies. You can follow the FlutterFire documentation for FCM to set this up.

Once you have set up FCM, you can handle incoming notifications in the onMessage, onResume, and onLaunch stream listeners of FirebaseMessaging. Below is an example of how to display a local notification when a Firebase notification is received in both the foreground and background:

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  // handle incoming message in the foreground
  _displayLocalNotification(message.notification!.title!,
                             message.notification!.body!);
});

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  // handle incoming message when app is in the background and opened
  _displayLocalNotification(message.notification!.title!,
                             message.notification!.body!);
});

FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

Future<dynamic> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // handle incoming message when app is terminated
  _displayLocalNotification(message.notification!.title!,
                             message.notification!.body!);

  // required to return a future
  return Future<void>.value();
}

void _displayLocalNotification(String title, String body) {
  // use flutter_local_notifications package to display local notification
  // configure notification details here
  flutterLocalNotificationsPlugin.show(
    id, 
    title, 
    body, 
    notificationDetails, 
  );
}

In the code above, we handle incoming notifications in the onMessage, onMessageOpenedApp, and onBackgroundMessage listeners of FirebaseMessaging. In each case, we call the _displayLocalNotification function to display a local notification using the flutter_local_notifications package.

Note that handling notifications in the background requires some additional configurations such as setting up a background isolate and registering it with FirebaseMessaging. You can follow the FlutterFire guide for handling background messages for more details.