flutterdartmobxprovider

Why should I use Provider in Mobx Flutter?


The official Mobx documentation for Flutter says that in order to transfer data correctly, you must use a Provider and refer to the context to retrieve the data.

But why can't I just call the Mobx class at the root of the application and access the global variable to get the data?

CbtStore cbt = CbtStore();

void main() async {
runApp(const MyApp());
}

Why should I be doing this?

void main() async {
runApp(MultiProvider(
         providers: [
           Provider<CbtStore>(create: (_) => CbtStore()),
           ],
      child: MyApp()));
}

And how do I refer to Mobx inside the widget methods in that case, for example, if I want to call the action in the Mobx class in initState method? Now I do it in the following way. But when using Provider in initState there is no context.

@override
  void initState() {
    cbt.init();
    super.initState();
  }

Solution

  • Provider is used only for dependency injection with mobx. It is not used for state changes.

    Now when you are using mobx you don't need a stateful widget in most cases because you are handling your state changes inside your mobx store and if there is any changes in the state we use Observer to change ui.

    if want something to initialise with the screen than prefer using constructor of mobx class rather then initState.

    for example,

    class MyStore = _MyStore with _$MyStore;
    
    abstract class _MyStore with Store {
    
    _MyStore(){
      getData();
    }
    }
    

    Now don't use global providers for your all of store. Only Initialise a provider whenever you need it. So when you push a route wrap it with a provider so that Provider.of(context); can find it. Only use global store if it required globally.

    You mentioned creating an instance of store to use it. When you initialise a store in stateless widget it, the data will get destroyed when you close the screen and when you reopen it everything will start all over again. It is useful when you don't need to maintain state after screen pops. It will based on your use case.