Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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.

like image 460
mbartn Avatar asked Sep 05 '18 13:09

mbartn


2 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())
  );
}
like image 168
rmtmckenzie Avatar answered Nov 13 '22 06:11

rmtmckenzie


Initialize navigatorState globalkey

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

navigatorKey.currentState.push(
    MaterialPageRoute(builder: (_) => classname())
  );
like image 21
Sanal Kv Avatar answered Nov 13 '22 06:11

Sanal Kv