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 1:

You should do what works best for your use case.

The reason why providers are useful is that they can be provided where needed. This could be in the application root, but also somewhere deeper in the widget tree.

Another advantage of the providers is that you can have a provider that notifies listeners. Widgets will rebuild automatically in this case, which can be useful if you have stored and need data to update everywhere in the application.

The initState does indeed not allow the use of providers directly. There are 3 solutions for this:

  1. Don't have the provider listing (Provider.of(context, listen: false); This allows you to use the methods, but not listen to changes.
  2. Use the provider in the build method, using the consumer.

I am by no means an expert on flutter, but this is just what I have experienced so far.