How to navigate to specific MaterialPageRoute in a

2019-04-15 05:06发布

问题:

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.

回答1:

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() {
  Navigator.push(navigatorKey.currentContext, MaterialPageRoute(builder: (_) => DeeplyNestedView()));
}


标签: dart flutter