Search code examples
flutterprovider

Flutter: accessing providers from other providers


For my flutter project, I am using the following multiple providers below:

@override
Widget build(BuildContext context) {
return MultiProvider(
  providers: [
    ChangeNotifierProvider<FirstProvider>(
      create: (context) => FirstProvider(),
    ),
    ChangeNotifierProvider<SecondProvider>(
      create: (context) => SecondProvider(),
    ),
    ChangeNotifierProvider<ThirdProvider>(
      create: (context) => ThirdProvider(),
    ),
    ChangeNotifierProvider<FourthProvider>(
      create: (context) => FourthProvider(),
    ),
  ],
  child: const MainApp(),
 );
}

Because sometimes I need to either get data or call functions from different providers from another provider, I am using it like this:

//First Provider
class FirstProvider with ChangeNotifier { 
  
 void callFunctionFromSecondProvider({
   required BuildContext context,
 }) {

  //Access the SecondProvider
  final secondProvider= Provider.of<SecondProvider>(
    context,
    listen: false,
  );

   secondProvider.myFunction();
 }
}

 
//Second Provider
class SecondProvider with ChangeNotifier { 
  bool _currentValue = true;

   void myFunction(){
     //Do something
   }

}

The callFunctionFromSecondProvider()of the FirstProvider is called from a widget and it will call myFunction() successfully, most of times.

Depending on the complexity of the function, I am sometimes experiencing that I can't access the SecondProvider, presumably due to context being null, when the widget state changes.

I am reading some documents online regarding provider, and they are suggesting changenotifierproxyprovider for what I understood as 1 to 1 provider relationship.

However, in my case, one provider needs to be accessed by multiple providers and vice versa.

Question:

Is there a more appropriate way that I can approach my case where one provider can be accessed by multiple providers?

EDIT:

Accessing provider should also be able to access different variable values without creating a new instance.


Solution

  • Alright.

    So it looks like Riverpod by the same author is the way to go as it addresses alot of flaws such as Provider being dependent on the widget tree, in my case, where the underlying issue came from.

    —--------

    For the time being, I still need to use the provider and for a quick and dirty solution, I am providing the context of not only the current widget that I am trying to access the provider, but also passing the parent context of the widget directly, so that in case a modal (for example) is closed, then any subsequent provider call can still be executed using the parent context.

    Hope this helps.