ChangeNotifierProvider vs ChangeNotifierProvider.value

后端 未结 4 1922
悲&欢浪女
悲&欢浪女 2020-12-17 15:24

I am quite new to this framework and working on state management using provider package where I come across ChangeNotifierProvider and ChangeNotifierProvi

4条回答
  •  星月不相逢
    2020-12-17 15:58

    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 extends ChangeNotifier implements ValueListenable {
      /// 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.

提交回复
热议问题