Home > Software design >  Flutter - How to navigate on notification when app is closed
Flutter - How to navigate on notification when app is closed

Time:05-20

How do you navigate in flutter when you open a notification when the app is closed?

This is my code which I call from the main function:

final FirebaseMessaging _fcm = FirebaseMessaging.instance;
_fcm.getInitialMessage().then((RemoteMessage message) { 
  if (message != null && message.data != null) {
      Keys.navKey.currentState.pushNamed(Routes.messageDetail);
  } 
}); 

In my main.dart I set the navigatorKey of my MaterialApp:

 MaterialApp(
          navigatorKey: Keys.navKey,)

And navKey is a static variable:

class Keys {
  static final navKey = new GlobalKey<NavigatorState>();
}

If I open a notification when the app is closed, I receive this error:

NoSuchMethodError: The method 'pushNamed' was called on null. Receiver: null Tried calling: pushNamed("MESSAGEDETAIL")

I can navigate elsewhere in the app with the navigation key.

Is there another way to do this or how can I make sure the navigationKey is initialized?

CodePudding user response:

use FirebaseMessaging.instance.getInitialMessage() to handle message in background

Example:

void handleMessageOnBackground() {
    FirebaseMessaging.instance.getInitialMessage().then(
      (remoteMessage) {
        if (remoteMessage != null) {
          String payload = json.encode(remoteMessage.data);
          //navigator two orther screen
        }
      },
    );
  }

And init handleMessageOnBackground() in home_screen.dart , not main.dart

main.dart > splash_screen > home_screen

  • Related