如何从Flutter中的通知导航到应用程序中的特定MaterialPageRoute
问题内容:
是否可以通过通知单击导航到应用程序中的特定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()));
}
问题是,当我像这样配置它时,它只能从配置通知的窗口小部件中唤醒(我猜这是因为在Navigator.push()中使用了“上下文”。是否有某种方法可以从菜单中的任何位置访问MaterialPageRoute应用程序而不使用任何上下文?
预先感谢您的回答。
问题答案:
在很多情况下,使用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())
);
}