From the docs I understood that one can call addListener()
on a ChangeNotifier instance to add a custom listener to the stack.
This method accepts a callback with zero arguments (according to notifyListeners()), e.g.:
class MyClass extends ChangeNotifier {
MyClass() {
addListener(() {
// ...
});
}
}
From within the callback, how does one find out what properties or parts of MyClass
have been changed?
ChangeNotifier is a class that provides change notification to its listeners. That means you can subscribe to a class that is extended or mixed in with ChangeNotifier and call its notifyListeners() method when there's a change in that class.
ChangeNotifierProvider is the widget that provides an instance of a ChangeNotifier to its descendants. It comes from the provider package. We already know where to put ChangeNotifierProvider : above the widgets that need to access it.
ChangeNotifier
does not have such capabilities inherently. You will have to implement your own logic. Specifically, you either have access to all of the properties of your ChangeNotifier
implementation because you add the listener in its scope or you have access to it because you have a reference to it in your scope.
ChangeNotifier
simply implements Listenable
and provides some utilities for managing listeners. Furthermore, the documentation states the following about it:
ChangeNotifier is optimized for small numbers (one or two) of listeners. It is O(N) for adding and removing listeners and O(N²) for dispatching notifications (where N is the number of listeners).
I am not sure about options with better runtime complexity for notifying listeners, but you will not run into any issues in a regular Flutter app.
ValueNotifier
is a pre-made implementation of ChangeNotifier
that will notify its listeners when its value
property is changed.
This is sufficient for most case, but since it appears that you want to create a custom ChangeNotifier
, you can use the source code of ValueNotifier
to take a look at an example implementation (it is very straight forward).
If you are just looking to do state management in general, ValueNotifier
s usually work great. However, they are not applicable in every scenario. Hence, here is an extensive list with different state management options.
Considering the questions, I think the techniques that fit your needs best and the most popular options are the following:
InheritedWidget as it lets you notify dependents based on what data changed. Additionally, there is InheritedModel as an extension of this and InheritedNotifier that works with Listenable
, just like ChangeNotifier
does.
The BLOC pattern, which works with streams.
The provider
package which is mostly a convenience wrapper for various Flutter state management techniques (InheritedWidget
, StatefulWidget
, ValueNotifier
, etc.).
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