问题
I am quite new to this framework and working on state management using provider package where I come across changeNotifierProvider
and ChangeNotifierProvider.value
but I am unable to distinguish their use case.
I had used ChangeNotifierProvider
in place of ChangeNotifierProvider.value
but doesn't work as intended.
回答1:
Does the official documentation help?
DO use ChangeNotifierProvider.value to provider an existing
ChangeNotifier
:
ChangeNotifierProvider.value(
value: variable,
child: ...
)
DON'T reuse an existing
ChangeNotifier
using the default constructor.
ChangeNotifierProvider(
builder: (_) => variable,
child: ...
)
Also check out this Github issue from the author about this.
回答2:
ValueNotifier and ChangeNotifier are closely related.
In fact, ValueNotifier is a subclass of ChangeNotifier that implements ValueListenable.
This is the implementation of ValueNotifier in the Flutter SDK:
/// A [ChangeNotifier] that holds a single value.
///
/// When [value] is replaced with something that is not equal to the old
/// value as evaluated by the equality operator ==, this class notifies its
/// listeners.
class ValueNotifier<T> extends ChangeNotifier implements ValueListenable<T> {
/// Creates a [ChangeNotifier] that wraps this value.
ValueNotifier(this._value);
/// The current value stored in this notifier.
///
/// When the value is replaced with something that is not equal to the old
/// value as evaluated by the equality operator ==, this class notifies its
/// listeners.
@override
T get value => _value;
T _value;
set value(T newValue) {
if (_value == newValue)
return;
_value = newValue;
notifyListeners();
}
@override
String toString() => '${describeIdentity(this)}($value)';
}
So, when should we use ValueNotifier vs ChangeNotifier?
Use ValueNotifier if you need widgets to rebuild when a simple value changes. Use ChangeNotifier if you want more control on when notifyListeners() is called.
来源:https://stackoverflow.com/questions/57335980/changenotifierprovider-vs-changenotifierprovider-value