diff --git a/packages/flutter/lib/src/foundation/change_notifier.dart b/packages/flutter/lib/src/foundation/change_notifier.dart index 363335f2df..5e9822a638 100644 --- a/packages/flutter/lib/src/foundation/change_notifier.dart +++ b/packages/flutter/lib/src/foundation/change_notifier.dart @@ -37,6 +37,10 @@ abstract class Listenable { /// [ChangeNotifier] is optimised 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). +/// +/// See also: +/// +/// * [ValueNotifier], which is a [ChangeNotifier] that wraps a single value. class ChangeNotifier extends Listenable { ObserverList _listeners = new ObserverList(); @@ -155,3 +159,23 @@ class _MergingListenable extends ChangeNotifier { super.dispose(); } } + +/// A [ChangeNotifier] that holds a single value. +/// +/// When [value] is replaced, this class notifies its listeners. +class ValueNotifier extends ChangeNotifier { + /// Creates a [ChangeNotifier] that wraps this value. + ValueNotifier(this._value); + + /// The current value stored in this notifier. + /// + /// When the value is replaced, this class notifies its listeners. + T get value => _value; + T _value; + set value(T newValue) { + if (_value == newValue) + return; + _value = newValue; + notifyListeners(); + } +} diff --git a/packages/flutter/test/foundation/change_notifier_test.dart b/packages/flutter/test/foundation/change_notifier_test.dart index 24cb71bf47..73e036e82e 100644 --- a/packages/flutter/test/foundation/change_notifier_test.dart +++ b/packages/flutter/test/foundation/change_notifier_test.dart @@ -190,4 +190,20 @@ void main() { expect(() { source.dispose(); }, throwsFlutterError); expect(() { source.notify(); }, throwsFlutterError); }); + + test('Value notifier', () { + final ValueNotifier notifier = new ValueNotifier(2.0); + + final List log = []; + final VoidCallback listener = () { log.add(notifier.value); }; + + notifier.addListener(listener); + notifier.value = 3.0; + + expect(log, equals([ 3.0 ])); + log.clear(); + + notifier.value = 3.0; + expect(log, isEmpty); + }); }