changenotifierProvider vs ChangeNotifierProvider.value

此生再无相见时 提交于 2020-04-14 12:13:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!