如何从Flutter中的通知导航到应用程序中的特定MaterialPageRoute

问题描述 投票:1回答:1

是否可以通过点击通知导航到应用中的特定MaterialPageRoute?我在主屏幕中配置了通知:

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

问题是,当我像这样配置它时,它只能从我配置通知的Widget(我想这是因为在Navigator.push()中使用'context'。有没有办法从任何地方访问MaterialPageRoute app没有使用任何上下文?

提前感谢您的回答。

dart flutter
1个回答
4
投票

使用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() {
  Navigator.push(navigatorKey.currentContext, MaterialPageRoute(builder: (_) => DeeplyNestedView()));
}
© www.soinside.com 2019 - 2024. All rights reserved.