如何在flutter应用程序中无上下文地导航? [英] How to navigate without context in flutter app?

查看:57
本文介绍了如何在flutter应用程序中无上下文地导航?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 OneSignal 接收推送通知的应用程序.我做了一个通知打开处理程序,它应该在点击通知时打开特定的屏幕.我如何在没有上下文的情况下导航到屏幕.或者如何在应用程序启动时打开特定屏幕.我的代码:

I have an app that recieves push notification using OneSignal. I have made a notification opened handler that should open specific screen on click of the notification. How can i navigate to a screen without context. or how can I open specific screen on app startup. My code:

OneSignal.shared.setNotificationOpenedHandler((notification) {
  var notify = notification.notification.payload.additionalData;
  if (notify["type"] == "message") {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => DM(user: notify['id']),
      ),
    );
  }
  if (notify["type"] == "user") {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => Profileo(notify["id"]),
      ),
    );
  }
  if (notify["type"] == "post") {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => ViewPost(notify["id"]),
      ),
    );
  }
});

我可以在第一次打开应用程序时实现这一点,但如果我关闭应用程序,即使我重新打开它,它也只会打开主页.我想那是因为上下文发生了变化.

I am able to achieve this when the app is opened for the first time but It only opens the homepage If i close the app and even if I re-open it. I guess that is because the context is changed.

请帮忙!!

推荐答案

看这里:https://github.com/brianegan/flutter_redux/issues/5#issuecomment-361215074

您可以为导航设置全局键:

You can set a global key for your navigation:

final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();

将其传递给 MaterialApp:

Pass it to MaterialApp:

new MaterialApp(
      title: 'MyApp',
      onGenerateRoute: generateRoute,
      navigatorKey: navigatorKey,
    );

推送路线:

navigatorKey.currentState.pushNamed('/someRoute');

这篇关于如何在flutter应用程序中无上下文地导航?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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