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.
There aren't very many cases where a GlobalKey is a good idea to use, but this might be one of them.
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(),
),
);
}
}
And then to use it you access the navigatorKey.currentContext:
_goToDeeplyNestedView() {
navigatorKey.currentState.push(
MaterialPageRoute(builder: (_) => DeeplyNestedView())
);
}
Initialize navigatorState
globalkey
final GlobalKey<NavigatorState> navigatorKey = GlobalKey(debugLabel: "Main Navigator");
navigatorKey.currentState.push(
MaterialPageRoute(builder: (_) => classname())
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With