How does ValueListenableProvider differ from ChangeNotifierProvider?

41 views Asked by At

How does ValueListenableProvider differ from ChangeNotifierProvider? Here is one of the definitions of ValueListenableProvider:

This provider is used to provide a ValueListenable object to its descendants. ValueListenable is similar to ChangeNotifier, but it only notifies its listeners when the value changes.

But ChangeNotifier also notifies its listeners when its property changes, doesn't it?

Or is the implication that ValueListenable will automatically notify listeners without having to call notifyListeners?

1

There are 1 answers

0
Ravindra S. Patil On

ValueListenableProvider and ChangeNotifierProvider are both providers in the Flutter framework used for managing state. They have some differences in terms of the type of state they manage and how they notify consumers about state changes.

Type of State:

ValueListenableProvider manages state that implements the ValueListenable interface. ValueListenable is a class in Flutter that provides a way to listen for changes to a value.

ChangeNotifierProvider manages state that extends the ChangeNotifier class. ChangeNotifier is a class in Flutter that provides a way to notify listeners when the object has changed.

Usage:

ValueListenableProvider is useful when you have a value that can be listened to for changes, such as a ValueNotifier or any other custom class that implements ValueListenable.

ChangeNotifierProvider is useful when you have a class that extends ChangeNotifier and you want to notify listeners when the state of that object changes.

Read - ChangeNotifierProvider, ValueListenableProvider

ChangeNotifierProvider:

ChangeNotifierProvider(
  create: (_) => new MyChangeNotifier(),
  child: Container()
)

ValueListenableProvider:

ValueListenable<int> foo;

ValueListenableProvider<int>.value(
  valueListenable: foo,
  child: Container(),
);