FirebaseMessaging.instance.getInitialMessage() is not called in terminated state

Viewed 670

FirebaseMessaging.instance.getInitialMessage() is not called in terminated state when we click notification that contains message data like this ,instead it is displaying screen from splash screen

{ "registration_ids": [ ""

],


"data": {
    "title": "Flutter9 Object Notification.3...",
    "body": "this is flutter Data Object notification test message from",
    "android_channel_id": "dgdgsdfgs",
},
"android":{
    "priority":"high"
}

}

2 Answers

Given that you not displayed how you setup your fcm , here is how to go about it

/// Create a [AndroidNotificationChannel] for heads up notifications
late AndroidNotificationChannel channel;

/// Initialize the [FlutterLocalNotificationsPlugin] package.
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

/// To verify things are working, check out the native platform logs.
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.
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  print('Handling a background message ${message.messageId}');
}

in main.dart

WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);


// setup displaying notifications 

channel = const AndroidNotificationChannel(
      'high_importance_channel', // id
      'High Importance Notifications', // title// description
      importance: Importance.high,
    );

    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

    /// Create an Android Notification Channel.
    ///
    /// We use this channel in the `AndroidManifest.xml` file to override the
    /// default FCM channel to enable heads up notifications.
    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    /// Update the iOS foreground notification presentation options to allow
    /// heads up notifications.
    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );


handle message call this in your initstate

FirebaseMessaging.instance
        .getInitialMessage()
        .then((RemoteMessage? message) {
      if (message != null) {
        // do message things
      }
    });
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      showMessage(message: message);
    });
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;

      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
                android: AndroidNotificationDetails(
                  channel.id,
                  channel.name,
                ),
                iOS: IOSNotificationDetails(subtitle: notification.title)));
      }
    });

incase you need to navigate on receiving a message

void showMessage({required RemoteMessage message}) async {
    if (message.data['route'] == "mypage") {
      var myparams =  message.data['payload'];
      Navigator.of(context).push(MaterialPageRoute(
          fullscreenDialog: true,
          builder: (_) {
            return MyPage(
             params:myparams,
            );
          })); ...

With FCM, you can send two types of messages to clients:

  • Notification messages, are sometimes thought of as "display messages." These are handled by the FCM SDK automatically.
  • Data messages, which are handled by the client app. "

https://firebase.google.com/docs/cloud-messaging/concept-options

What you are trying to send is a data message, my best guess is that the firebase SDK does not recognize the data message so it does not trigger the firebase message event listener. Your notification must have a 'notification' field for firebase SDK to listen to.

Related