Mobx.dart: How to change navigation from within the store (access to context)

Created on 21 Mar 2019  路  3Comments  路  Source: mobxjs/mobx.dart

Context seems to change all the time in flutter, much like in android. So passing the context to my singleton to store and use is unreliable. In mobx-js I could update an observable and watch for that change in react's componentDidUpdate to make use of react-router-dom and change the route.

How should mobx handle needing access or trigger access to context in order to do something like change the route to the login page if a user's access credentials are revoked?

Could I "re-store" the context on every screen load into mobx as a non-observable? say from within initState()?

question

Most helpful comment

I have created a GlobalKey for the NavigatorState in main.dart

final myNavigatorKey = GlobalKey<NavigatorState>();
....
...
class _MyAppState extends State<MyApp>{
....
Widget build(BuildContext context)=> Provider<AppState>(
        value:state,
        child:MaterialApp(
              navigatorKey:myNavigatorKey,
....
...
          )

}

Then within store you could do this myNavigatorKey.currentState.pushNamedAndRemoveUntil('mynewRouteName',ModalRoute.withName('mynewRouteName'))

All 3 comments

One other option is to setup a reaction in the Widget itself (in the initState) to track any observable and then fire the navigation. You can make the context available as an argument to the action that you fire from within the reaction.

Essentially actions can take arguments, so you can pass the context as the required argument. Will have an example around this soon

I have created a GlobalKey for the NavigatorState in main.dart

final myNavigatorKey = GlobalKey<NavigatorState>();
....
...
class _MyAppState extends State<MyApp>{
....
Widget build(BuildContext context)=> Provider<AppState>(
        value:state,
        child:MaterialApp(
              navigatorKey:myNavigatorKey,
....
...
          )

}

Then within store you could do this myNavigatorKey.currentState.pushNamedAndRemoveUntil('mynewRouteName',ModalRoute.withName('mynewRouteName'))

Closing it for now

Was this page helpful?
0 / 5 - 0 ratings