unable to navigate to particular screen on push notification click when app is killed(Flutter android)

Viewed 1033

I m using firebase cloud messaging in my flutter application. I am unable to navigate to particular screen when I click on push notification. It is working fine when app is in foreground and app is background but not in case when app is killed.

code:

class FcmHelper {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  new FlutterLocalNotificationsPlugin();
  void initializeFcm() {
    var initializationSettingsAndroid =
    new AndroidInitializationSettings('@mipmap/ic_launcher');


    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: onSelectNotification);

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) {      
        displayNotification(message);
        return;
      },
      onResume: (Map<String, dynamic> message) {
        displayNotification(message);
        return;
      },
      onLaunch: (Map<String, dynamic> message) {
        displayNotification(message);
        return;
      },

    );
 
  }


  Future displayNotification(Map<String, dynamic> message) async {
    // display notification
  }

  Future onSelectNotification(String payload) async {
    try {
      await flutterLocalNotificationsPlugin.cancelAll();
      var tripDetails = HotelBookingDetails(
          );
      Navigator.pushAndRemoveUntil(
          GlobalVariable.navState.currentContext,
          MaterialPageRoute(builder: (context) => tripDetails),
          ModalRoute.withName('/'));
    } catch (e, s) {
      debugPrint(e.toString());
    }
  }

}
3 Answers

onLaunch callback will fire once FirebaseMessaging initialized, maybe you can navigate with navigatorKey like so

      GlobalVariable.navState.currentState.push(
                        MaterialPageRoute(
                          builder: (_) => YourPage(),
                        ),
                      );

if it does not help try to initialize FirebaseMessaging when context is available, maybe in MateriApp builder method

MaterialApp(
  builder: (context, widget) {
     FcmHelper().initializeFcm();
   }
);
final noti = FirebaseMessaging.instance.getInitialMessage();

You implement this in splash screen and go to your screen you want

FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage message) {
    // add your condition if any
    Navigator.of(context).pushNamedAndRemoveUntil("/notifications", (route) => route.settings.name == "/notifications" ? false : true);
});
Related