如何从Flutter中的通知导航到应用程序中的特定MaterialPageRoute [英] How to navigate to specific MaterialPageRoute in app from a notification in Flutter

查看:116
本文介绍了如何从Flutter中的通知导航到应用程序中的特定MaterialPageRoute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

问题是,当我这样配置时,它只能从我在其中配置通知的小部件(我猜这是因为在
Navigator.push()中使用了上下文。是否有某种方法可以从应用程序中的任何位置访问MaterialPageRoute,而无需使用任何上下文?

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?

在此先感谢您的回答。

推荐答案

在很多情况下,使用GlobalKey是一个好主意,但这可能是其中之一。

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

构建 MaterialApp 时(我假设您正在使用),则可以传入 navigatorKey 参数,该参数指定用于导航器的键。然后,您可以使用该键来访问导航器的状态,如下所示:

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

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

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

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

这篇关于如何从Flutter中的通知导航到应用程序中的特定MaterialPageRoute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆