首页 > 解决方案 > How to navigate to specific MaterialPageRoute in app from a notification in Flutter

问题描述

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.

标签: dartflutter

解决方案


使用 GlobalKey 是一个好主意的情况并不多,但这可能就是其中之一。

当您构建您的MaterialApp(我假设您正在使用)时,您可以传入一个navigatorKey参数,该参数指定用于导航器的键。然后,您可以使用此键访问导航器的状态。看起来像这样:

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(),
      ),
    );
  }
}

然后要使用它,您可以访问 navigatorKey.currentContext:

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

推荐阅读