both firebase and flutter local notifications handle background notificaiton

Viewed 571

I'm facing an issue with displaying double notifications when the app in the background firebase handle the notification first and then the flutter local notification display a popup on the screen anyway to make firebase not show the notification

p.s remove the
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);

make the app not handle notifications on background

FirebaseMessaging.onMessage.listen(
      (RemoteMessage? message) async {
      
        _showNotification(
            id: 0,
            title: message?.notification?.title ?? '',
            body: message?.notification?.body ?? '');
      },
    );

    FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);

firebaseMessagingBackgroundHandler:

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage? message) async {

  _showNotification(
      id: 0,
      title: message?.notification?.title ?? '',
      body: message?.notification?.body ?? '');

}

the firebase package contains title and body in the notification flag even if the app working in the background any way to make the notification only handled by flutter_local_notification package

3 Answers
  • One possible problem is the initialization of your local_notification_package

It should be a topmost initialization, i.e you initialize the flutter_local_notifications package and the android channel before calling _showNotification function

  • Another possible problem is the initialization of firebase. It should be done before the app runs, since it is a foreground notification

Your firebaseMessagingBackgroundHandler will look like.......

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage? message) async {
  await Firebase.initializeApp(); //initialize firebase
  //INITIALIZE YOUR FLUTTER LOCAL NOTIFICATION PACKAGE 
  // INITIALIZE YOUR ANDROID CHANNEL
  //then show the notification
  _showNotification(
      id: 0,
      title: message?.notification?.title ?? '',
      body: message?.notification?.body ?? '');

}

I experience the same problem until added

<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="high_importance_channel" />

in the android manifest file.

Also, keep in mind the value high_importance_channel could be any thing you want but it should be the same as the one you declare in your flutter code like below:

const AndroidNotificationChannel channel = AndroidNotificationChannel(
  'high_importance_channel', //channel id
  'High Importance Notifications', //title
  'This channel is used for important notifications.', //description
  importance: Importance.max,
);

You can find more info here

Related