Kaspi
Kaspi

Reputation: 3678

How do I use ChangeNotifier?

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?

Upvotes: 7

Views: 12498

Answers (1)

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126704

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

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, ValueNotifiers 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.).

Upvotes: 13

Related Questions