Closed acoutts closed 4 years ago
Forgot above, for my example with the classic navigator you also have to add this navigator key to WidgetsApp/MaterialApp/CupertinoApp:
WidgetsApp(
...
navigatorKey: GetIt.instance<NavigationService>().navigatorKey,
);
While not very recommended to rely on global state outside the Context to get the navigation instance, it's possible. For getting just the Nuvigator, you should be able to do the exact same thing but replacing the NavigatorState
with NuvigatorState
and passing as a key
property to the Nuvigator instance you want.
if you are using the >= 0.3.0 version of Nuvigator, you may be able to save the Router instance passed to the Nuvigator, and form the Router, you are able to use all the navigation methods, and also get the attached Nuvigator instance to it.
Thanks! Is there a better way I should do things do you think?
I have a state machine in a mobx store to describe the initial process of opening the app and logging the user in, and during some state transitions I need to trigger a navigation. I thought using a global navigator would work here, because I could for example have the following flow:
1) user fills in information and clicks login 2) navigate to loading screen -- At the same time, kick off API requests to pull the user profile / required information to populate the app's state. 3) After API requests are done, then navigate to the main authenticated landing screen.
I was able to access the Nuvigator instance as you said, but you're right this doesn't feel like a good idea. Mainly, there is a race condition here because if I try to access the Nuvigator too soon, it's still null. I did a simple test with a 2s timeout and it works, but of course I don't want to work around a race condition like this.
There are three main reasons why I would avoid this pattern:
I would suggest maybe to pass callbacks or event the router/nuvigator instance to the mobx handler, so it would just execute it
Thanks for that! Do you have any more details on your 2 suggestions for things I can read into?
I think I've got this figured out now, thanks for clarifying @leoiacovini !
With built-in navigator I used GetIt() and a global key to do this, how can I access Nuvigator to navigate screens outside of a build function?
Here's an example:
Run this just before
runApp()
NavigationService definition:
Then I can navigate from anywhere using this: