How to navigate to specific MaterialPageRoute in app from a notification in Flutter

Viewed 8866

Is it possible to navigate to specific MaterialPageRoute in app from notification click? I have notifications configured in the main screen:

void _configureNotifications() {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  _firebaseMessaging.requestNotificationPermissions();
  _firebaseMessaging.configure(
    onMessage: (Map<String, dynamic> message) {
      _goToDeeplyNestedView();
    },
    onLaunch: (Map<String, dynamic> message) {
      _goToDeeplyNestedView();
    },
    onResume: (Map<String, dynamic> message) {
      _goToDeeplyNestedView();
    },
  );
}

_goToDeeplyNestedView() {
  Navigator.push(
      context,
      MaterialPageRoute(
          builder: (_) => DeeplyNestedView()));
}

The problem is, that when i configure it like this, it woks only from Widget where i configured notifications (I guess it's because of using 'context' in Navigator.push(). Is there some way to access to MaterialPageRoute from anywhere in the app without using any context?

Thank you in advance for your answers.

3 Answers

There aren't very many cases where a GlobalKey is a good idea to use, but this might be one of them.

When you build your MaterialApp (which I assume you're using), you can pass in a navigatorKey parameter which specifies the key to use for the navigator. You can then use this key to access the navigator's state. That would look something like this:

class _AppState extends State<App> {
  final GlobalKey<NavigatorState> navigatorKey = GlobalKey(debugLabel: "Main Navigator");

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      navigatorKey: navigatorKey,
      home: new Scaffold(
        endDrawer: Drawer(),
        appBar: AppBar(),
        body: new Container(),
      ),
    );
  }
}

And then to use it you access the navigatorKey.currentContext:

_goToDeeplyNestedView() {
  navigatorKey.currentState.push(
    MaterialPageRoute(builder: (_) => DeeplyNestedView())
  );
}

Initialize navigatorState globalkey

final GlobalKey<NavigatorState> navigatorKey = GlobalKey(debugLabel: "Main Navigator");

navigatorKey.currentState.push(
    MaterialPageRoute(builder: (_) => classname())
  );

I was facing the same issue and fixed it using the below code :

  1. Creating 1 global key like :

    final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey();
    
  2. Assigning the key to Scaffold in build method :

    return Scaffold( key: _scaffoldKey,
    appBar: Container(), body:
    Container() );
    
  3. printing ('something') before this to make sure your app is reaching to below code:

    Navigator.push(
            _scaffoldKey.currentContext,
            MaterialPageRoute(
                builder: ( _) =>
                    NotificationDetailEn(notificationModel: model)));
    

I think it will be helpful.

Related