Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to navigate without context in flutter app?

Tags:

flutter

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.

Please Help!!

like image 672
Ashutosh Sharma Avatar asked Oct 24 '18 06:10

Ashutosh Sharma


People also ask

What is navigatorKey in Flutter?

navigatorKey. A key to use when building the Navigator. If a navigatorKey is specified, the Navigator can be directly manipulated without first obtaining it from a BuildContext via Navigator. of: from the navigatorKey, use the GlobalKey. currentState getter.

What is Pushreplacement in Flutter?

Replace the current route of the navigator that most tightly encloses the given context by pushing the given route and then disposing the previous route once the new route has finished animating in.


2 Answers

Look at this here: https://github.com/brianegan/flutter_redux/issues/5#issuecomment-361215074

You can set a global key for your navigation:

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

Pass it to MaterialApp:

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

Push routes:

navigatorKey.currentState.pushNamed('/someRoute'); 
like image 88
tsdevelopment Avatar answered Sep 23 '22 07:09

tsdevelopment


You can use this wonderful plugin: https://pub.dev/packages/get

Description from the package: A consistent navigation library that lets you navigate between screens, open dialogs, and display snackbars from anywhere in your code without context.

Get.to(NextScreen()); // look at this simplicity :) Get.back(); //  pop() Get.off(NextScreen()); // clears the previous routes and opens a new screen. 
like image 27
y.selimdogan Avatar answered Sep 20 '22 07:09

y.selimdogan