Flutter newbie here, I'm currently using Provider for my state management and had a few questions as to how it actually works.
I am declaring my providers like this...
main.dart
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider<ProviderFoo>(create: (_) => ProviderA(),
ChangeNotifierProvider<ProviderBar>(create: (_) => ProviderB(),
],
),
);
Both ProviderFoo and ProviderBar classes extend ChangeNotifier.
Question 1:
If I have 2 different views and I need to use FooProvider on both of the views as so
widget1.dart
var providerOneFoo = Provider.of<FooProvider>(context);
widget2.dart
var providerTwoFoo = Provider.of<FooProvider>(context);
Is providerOneFoo the same as providerTwoFoo even if they are on two separate files? Is the Provider.of creating a new instance of the provider or just referencing the global instance that was set at the top of the widget tree where we declared them in MultiProviders?
Question 2:
Is there any design flaw if I pass in a provider as a parameter for a function in another provider?
widget1.dart
var fooProvider = Provider.of<FooProvider>(context);
var barProvider = Provider.of<BarProvider>(context);
fooProvider.someFunction(barProvider);
provider_foo.dart
class FooProvider extends ChangeNotifier{
...
void someFunction(barProvider) {
barProvider.someVar = 0;
notifyListeners();
}
}
If that is possible, can I make an external provider an attribute of another provider?
Thanks :)
CodePudding user response:
Question 1
Using Provider<ProviderClass>.of(context)
always references the same global provider provided (No pun intended)
Question 2
It would be better to implement the method on providerBar
and call notifyListeners()
from it.
In your example, calling notifyListeners()
in FooProvider
will only notify listners of FooProvider.
If some widget depended on BarProvider
, in your example, it would not be notified of the change to barProvider.someVar