change_notifier.dart 11.5 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:collection';

7
import 'package:meta/meta.dart';
8 9 10

import 'assertions.dart';
import 'basic_types.dart';
11
import 'diagnostics.dart';
Ian Hickson's avatar
Ian Hickson committed
12 13

/// An object that maintains a list of listeners.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
///
/// The listeners are typically used to notify clients that the object has been
/// updated.
///
/// There are two variants of this interface:
///
///  * [ValueListenable], an interface that augments the [Listenable] interface
///    with the concept of a _current value_.
///
///  * [Animation], an interface that augments the [ValueListenable] interface
///    to add the concept of direction (forward or reverse).
///
/// Many classes in the Flutter API use or implement these interfaces. The
/// following subclasses are especially relevant:
///
///  * [ChangeNotifier], which can be subclassed or mixed in to create objects
///    that implement the [Listenable] interface.
///
///  * [ValueNotifier], which implements the [ValueListenable] interface with
///    a mutable value that triggers the notifications when modified.
///
/// The terms "notify clients", "send notifications", "trigger notifications",
/// and "fire notifications" are used interchangeably.
///
/// See also:
///
///  * [AnimatedBuilder], a widget that uses a builder callback to rebuild
///    whenever a given [Listenable] triggers its notifications. This widget is
42 43 44 45
///    commonly used with [Animation] subclasses, hence its name, but is by no
///    means limited to animations, as it can be used with any [Listenable]. It
///    is a subclass of [AnimatedWidget], which can be used to create widgets
///    that are driven from a [Listenable].
46 47 48 49 50 51 52 53 54
///  * [ValueListenableBuilder], a widget that uses a builder callback to
///    rebuild whenever a [ValueListenable] object triggers its notifications,
///    providing the builder with the value of the object.
///  * [InheritedNotifier], an abstract superclass for widgets that use a
///    [Listenable]'s notifications to trigger rebuilds in descendant widgets
///    that declare a dependency on them, using the [InheritedWidget] mechanism.
///  * [new Listenable.merge], which creates a [Listenable] that triggers
///    notifications whenever any of a list of other [Listenable]s trigger their
///    notifications.
Ian Hickson's avatar
Ian Hickson committed
55 56 57 58 59 60 61 62 63 64
abstract class Listenable {
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const Listenable();

  /// Return a [Listenable] that triggers when any of the given [Listenable]s
  /// themselves trigger.
  ///
  /// The list must not be changed after this method has been called. Doing so
  /// will lead to memory leaks or exceptions.
65
  ///
66
  /// The list may contain nulls; they are ignored.
67
  factory Listenable.merge(List<Listenable?> listenables) = _MergingListenable;
Ian Hickson's avatar
Ian Hickson committed
68 69 70 71 72 73 74 75

  /// Register a closure to be called when the object notifies its listeners.
  void addListener(VoidCallback listener);

  /// Remove a previously registered closure from the list of closures that the
  /// object notifies.
  void removeListener(VoidCallback listener);
}
76

77 78 79 80
/// An interface for subclasses of [Listenable] that expose a [value].
///
/// This interface is implemented by [ValueNotifier<T>] and [Animation<T>], and
/// allows other APIs to accept either of those implementations interchangeably.
81 82 83 84 85 86
///
/// See also:
///
///  * [ValueListenableBuilder], a widget that uses a builder callback to
///    rebuild whenever a [ValueListenable] object triggers its notifications,
///    providing the builder with the value of the object.
87
abstract class ValueListenable<T> extends Listenable {
88 89 90 91
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const ValueListenable();

92 93 94 95 96
  /// The current value of the object. When the value changes, the callbacks
  /// registered with [addListener] will be invoked.
  T get value;
}

97 98 99 100 101
class _ListenerEntry extends LinkedListEntry<_ListenerEntry> {
  _ListenerEntry(this.listener);
  final VoidCallback listener;
}

102 103
/// A class that can be extended or mixed in that provides a change notification
/// API using [VoidCallback] for notifications.
104
///
105
/// It is O(1) for adding listeners and O(N) for removing listeners and dispatching
106
/// notifications (where N is the number of listeners).
Adam Barth's avatar
Adam Barth committed
107 108 109 110
///
/// See also:
///
///  * [ValueNotifier], which is a [ChangeNotifier] that wraps a single value.
111
class ChangeNotifier implements Listenable {
112
  LinkedList<_ListenerEntry>? _listeners = LinkedList<_ListenerEntry>();
113

114 115
  bool _debugAssertNotDisposed() {
    assert(() {
116
      if (_listeners == null) {
117 118 119 120
        throw FlutterError(
          'A $runtimeType was used after being disposed.\n'
          'Once you have called dispose() on a $runtimeType, it can no longer be used.'
        );
121 122
      }
      return true;
123
    }());
124 125 126
    return true;
  }

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  /// Whether any listeners are currently registered.
  ///
  /// Clients should not depend on this value for their behavior, because having
  /// one listener's logic change when another listener happens to start or stop
  /// listening will lead to extremely hard-to-track bugs. Subclasses might use
  /// this information to determine whether to do any work when there are no
  /// listeners, however; for example, resuming a [Stream] when a listener is
  /// added and pausing it when a listener is removed.
  ///
  /// Typically this is used by overriding [addListener], checking if
  /// [hasListeners] is false before calling `super.addListener()`, and if so,
  /// starting whatever work is needed to determine when to call
  /// [notifyListeners]; and similarly, by overriding [removeListener], checking
  /// if [hasListeners] is false after calling `super.removeListener()`, and if
  /// so, stopping that same work.
  @protected
  bool get hasListeners {
    assert(_debugAssertNotDisposed());
145
    return _listeners!.isNotEmpty;
146 147
  }

148
  /// Register a closure to be called when the object changes.
149
  ///
150 151 152 153
  /// If the given closure is already registered, an additional instance is
  /// added, and must be removed the same number of times it is added before it
  /// will stop being called.
  ///
154
  /// This method must not be called after [dispose] has been called.
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
  ///
  /// {@template flutter.foundation.ChangeNotifier.addListener}
  /// If a listener is added twice, and is removed once during an iteration
  /// (e.g. in response to a notification), it will still be called again. If,
  /// on the other hand, it is removed as many times as it was registered, then
  /// it will no longer be called. This odd behavior is the result of the
  /// [ChangeNotifier] not being able to determine which listener is being
  /// removed, since they are identical, therefore it will conservatively still
  /// call all the listeners when it knows that any are still registered.
  ///
  /// This surprising behavior can be unexpectedly observed when registering a
  /// listener on two separate objects which are both forwarding all
  /// registrations to a common upstream object.
  /// {@endtemplate}
  ///
  /// See also:
  ///
  ///  * [removeListener], which removes a previously registered closure from
  ///    the list of closures that are notified when the object changes.
174
  @override
175
  void addListener(VoidCallback listener) {
176
    assert(_debugAssertNotDisposed());
177
    _listeners!.add(_ListenerEntry(listener));
178 179 180 181
  }

  /// Remove a previously registered closure from the list of closures that are
  /// notified when the object changes.
182 183 184 185
  ///
  /// If the given listener is not registered, the call is ignored.
  ///
  /// This method must not be called after [dispose] has been called.
186
  ///
187
  /// {@macro flutter.foundation.ChangeNotifier.addListener}
188
  ///
189 190 191 192
  /// See also:
  ///
  ///  * [addListener], which registers a closure to be called when the object
  ///    changes.
193
  @override
194
  void removeListener(VoidCallback listener) {
195
    assert(_debugAssertNotDisposed());
196 197 198 199 200 201
    for (final _ListenerEntry entry in _listeners!) {
      if (entry.listener == listener) {
        entry.unlink();
        return;
      }
    }
202 203
  }

204 205 206 207
  /// Discards any resources used by the object. After this is called, the
  /// object is not in a usable state and should be discarded (calls to
  /// [addListener] and [removeListener] will throw after the object is
  /// disposed).
208 209 210 211
  ///
  /// This method should only be called by the object's owner.
  @mustCallSuper
  void dispose() {
212
    assert(_debugAssertNotDisposed());
213
    _listeners = null;
214 215 216 217 218
  }

  /// Call all the registered listeners.
  ///
  /// Call this method whenever the object changes, to notify any clients the
219 220 221
  /// object may have changed. Listeners that are added during this iteration
  /// will not be visited. Listeners that are removed during this iteration will
  /// not be visited after they are removed.
222 223 224
  ///
  /// Exceptions thrown by listeners will be caught and reported using
  /// [FlutterError.reportError].
225 226
  ///
  /// This method must not be called after [dispose] has been called.
227
  ///
228
  /// Surprising behavior can result when reentrantly removing a listener (e.g.
229 230
  /// in response to a notification) that has been registered multiple times.
  /// See the discussion at [removeListener].
231
  @protected
232
  @visibleForTesting
233
  void notifyListeners() {
234
    assert(_debugAssertNotDisposed());
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    if (_listeners!.isEmpty)
      return;

    final List<_ListenerEntry> localListeners = List<_ListenerEntry>.from(_listeners!);

    for (final _ListenerEntry entry in localListeners) {
      try {
        if (entry.list != null)
          entry.listener();
      } catch (exception, stack) {
        FlutterError.reportError(FlutterErrorDetails(
          exception: exception,
          stack: stack,
          library: 'foundation library',
          context: ErrorDescription('while dispatching notifications for $runtimeType'),
          informationCollector: () sync* {
            yield DiagnosticsProperty<ChangeNotifier>(
              'The $runtimeType sending notification was',
              this,
              style: DiagnosticsTreeStyle.errorProperty,
            );
          },
        ));
258 259 260 261
      }
    }
  }
}
Ian Hickson's avatar
Ian Hickson committed
262

263 264
class _MergingListenable extends Listenable {
  _MergingListenable(this._children);
Ian Hickson's avatar
Ian Hickson committed
265

266
  final List<Listenable?> _children;
Ian Hickson's avatar
Ian Hickson committed
267 268

  @override
269
  void addListener(VoidCallback listener) {
270
    for (final Listenable? child in _children) {
271 272 273 274 275 276
      child?.addListener(listener);
    }
  }

  @override
  void removeListener(VoidCallback listener) {
277
    for (final Listenable? child in _children) {
278 279
      child?.removeListener(listener);
    }
Ian Hickson's avatar
Ian Hickson committed
280
  }
281 282 283

  @override
  String toString() {
284
    return 'Listenable.merge([${_children.join(", ")}])';
285
  }
Ian Hickson's avatar
Ian Hickson committed
286
}
Adam Barth's avatar
Adam Barth committed
287 288 289

/// A [ChangeNotifier] that holds a single value.
///
290 291 292
/// 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.
293
class ValueNotifier<T> extends ChangeNotifier implements ValueListenable<T> {
Adam Barth's avatar
Adam Barth committed
294 295 296 297 298
  /// Creates a [ChangeNotifier] that wraps this value.
  ValueNotifier(this._value);

  /// The current value stored in this notifier.
  ///
299 300 301
  /// 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.
302
  @override
Adam Barth's avatar
Adam Barth committed
303 304 305 306 307 308 309 310
  T get value => _value;
  T _value;
  set value(T newValue) {
    if (_value == newValue)
      return;
    _value = newValue;
    notifyListeners();
  }
311 312

  @override
313
  String toString() => '${describeIdentity(this)}($value)';
Adam Barth's avatar
Adam Barth committed
314
}