Flutter - FirebaseMessaging.onMessageOpenedApp.listen is not triggered

Viewed 6996

I am using:

flutter version 2.2
firebase_messaging: ^10.0.2

I receive push notification, then click on it and the app is opened. Then I do not see FirebaseMessaging.onMessageOpenedApp.listen getting called (the callback is sending debug email to me, but I don't receive any)

My questions are

  1. (optional) How can I debug android app with android studio debugur simulating case above, so app is killed not opened, then is opened via notification

  2. What can be the issue here ? Why that stream is not triggered ? I initialise it in main.dart

PS: All other methods work fine, so if app is on foreground, onMessage.listen works great. I need to handle onMessageOpenedApp so I can redirect user to proper view based on notification information

2 Answers

For the first question:

To view the logs from your app, you can use the 'Logcat' tab in Android Studio or IntelliJ: enter image description here

For the second question:

If your app is terminated and you want to receive a notification click callback, you should use:

FirebaseMessaging.instance.getInitialMessage().then((message) {
  if (message != null) {
    // DO YOUR THING HERE
  }
});

, because according to the Flutter team's comments for onMessageopenedApp function:

 /// If your app is opened via a notification whilst the app is terminated,
  /// see [getInitialMessage].

To view logs when app is killed in your case, have you tried flutter logs command, just plug in your device in usb debugging and run flutter logs in you terminal all your print messages will show up here.

with regard to FirebaseMessaging.onMessageOpenedApp.listen getting called when app is launched is because you need to define the background messaging handler

/// Define a top-level named handler which background/terminated messages will
/// call.
///
/// 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();
  print('Handling a background message ${message.messageId}');
}

check the complete firebase_messaging example here main.dart

Related