whats the difference between these 2 widgets and its necessary to use ChangeNotifier
in every Provider
or there is many ways to use Provider
?
Provider exposes a value down the widget tree so that children can have access to it, regardless their location (but still, they must be at least one level below the provider). Generally you use a provider to expose a "cache" to a series of widgets or as a neat way of sharing data across multiple pages. Note that:
By default, when reading a value stored in a provider, nothing happens. It means that if you're exposing a class and you change some internals of it, children won't listen to it.
If your class exposed via provider mixes with ChangeNotifier
then you've the possibility to rebuild listeners when something changes.
You are absolutely not forced to use ChangeNotifier
in your model classes exposed by a provider. Use it when you need some widgets to listen to changes but if that's not the case, just ignore it.
Example 1 - (no ChangeNofitier)
You are using a TabBarView
to work with tabs (let's say you have 3 pages) and your pages need to share some data. Instead of sharing data using a Navigator
, which can become cumbersome, go for a provider.
class MyDataHolder {
int _value = 0;
void updateValue(int a) {
_value = a;
}
}
And then do something like this:
Provider<MyDataHolder>(
create: (_) => MyDataHolder(),
child: MyWidgetWithTabs(),
)
In this way you can easily share data among pages
Example 2 - (with ChangeNotifier)
Still the above case but if you want your pages to listen to changes on a particular data, then use a notifier. Like this:
class MyDataHolder with ChangeNotifier {
int _value = 0;
void updateValue(int a) {
_value = a;
notifyListeners();
}
}
Now children listen to changes. Differently from before, when calling updateValue
listeners will be rebuilt.
So both ways are good but they have different purposes. If you don't need a series of listeners to be rebuilt in response to updates, just don't use ChangeNotifier
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With