dart - 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.
解决方案
使用 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())
);
}
推荐阅读
- security - 没有 SSL 的网站显示不需要的广告,添加 SSL 后它们就消失了。是什么导致出现不需要的内容?
- r - 在具有不同包的 git 分支之间切换时的 packrat 恢复
- json - 反应原生:导入具有动态文件名的文件
- c++ - 不明白用双指针创建二维动态数组 (**)
- javascript - react-native-maps 无法在无状态组件中引用 MapView
- javascript - 如何在页面打开时停止调用函数
- c# - 无法向变量添加数字(Unity 新手)
- angular - 动态添加控件以形成角度
- ios - 在 iOS 13 中崩溃
- tar - 焦油不使用 -P 标志提取