在Flutter应用中如何在没有上下文的情况下进行导航? [英] How to navigate without context in flutter app?
问题描述
我有一个应用程序可以使用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屋!