I am trying Implemented push notification service using Firebase Cloud Messaging in my Flutter app. This is how FCM documentation says we should handle notifications, according to the current state (foreground, background or terminated) of our app:
Foreground: we have an onMessage
stream, that we can listen to, but FCM will not show any notification when in foreground state, so we have to use FlutterLocalNotificationsPlugin
for that, this is my implementation of it:
FirebaseMessaging.onMessage.listen((RemoteMessage remoteMessage) {
// calling flutter local notifications plugin for showing local notification
scheduleNotification(remoteMessage);
});
in scheduleNotification
method I call the FlutterLocalNotificationsPlugin().show()
method, and everything works as expected till now.
The problem starts here:
Background, Terminated: Firebase automatically shows a notification in this state and it has a onBackgroundMessage. method, to which we can pass an BackgroundMessageHandler which runs after FCM has shown the notification. This is my implementation of the background handler:
Future<void> backgroundMessageHandler(
RemoteMessage remoteMessage) async {
RemoteNotification? remoteNotification = remoteMessage.notification;
if (remoteNotification != null) {
FlutterLocalNotificationsPlugin().show(
remoteMessage.messageId.hashCode,
remoteNotification.title,
remoteNotification.body,
NotificationDetails(
android: AndroidNotificationDetails(
_androidNotificationChannel.id,
_androidNotificationChannel.name,
_androidNotificationChannel.description,
icon: 'launch_background',
importance: Importance.max),
));
}
}
Problem: Every time my app receives a notification from FCM, my app shows TWO notifications, one is shown automatically by FCM, and the second one is shown by the FlutterLocalNotificationsPlugin().show()
method that i am calling in the BackgroundMessageHandler
.
Tl:dr
How do I prevent FCM to show any notifications automatically and only show it via FlutterLocalNotificationsPlugin().show()
method ?
One solution is, I don't send notifications from FCM and only send Data Messages, for which FCM doesn't show any notification. but, i don't think its the right way.