change_notifier.dart 15.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
import 'package:meta/meta.dart';
6 7 8

import 'assertions.dart';
import 'basic_types.dart';
9
import 'diagnostics.dart';
Ian Hickson's avatar
Ian Hickson committed
10 11

/// An object that maintains a list of listeners.
12 13 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
///
/// 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
40 41 42 43
///    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].
44 45 46 47 48 49 50 51 52
///  * [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
53 54 55 56 57 58 59 60 61 62
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.
63
  ///
64
  /// The list may contain nulls; they are ignored.
65
  factory Listenable.merge(List<Listenable?> listenables) = _MergingListenable;
Ian Hickson's avatar
Ian Hickson committed
66 67 68 69 70 71 72 73

  /// 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);
}
74

75 76 77 78
/// 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.
79 80 81 82 83 84
///
/// 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.
85
abstract class ValueListenable<T> extends Listenable {
86 87 88 89
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const ValueListenable();

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

95 96
/// A class that can be extended or mixed in that provides a change notification
/// API using [VoidCallback] for notifications.
97
///
98
/// It is O(1) for adding listeners and O(N) for removing listeners and dispatching
99
/// notifications (where N is the number of listeners).
Adam Barth's avatar
Adam Barth committed
100 101 102 103
///
/// See also:
///
///  * [ValueNotifier], which is a [ChangeNotifier] that wraps a single value.
104
class ChangeNotifier implements Listenable {
105 106 107 108 109
  int _count = 0;
  List<VoidCallback?> _listeners = List<VoidCallback?>.filled(0, null);
  int _notificationCallStackDepth = 0;
  int _reentrantlyRemovedListeners = 0;
  bool _debugDisposed = false;
110

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

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
  /// 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());
142
    return _count > 0;
143 144
  }

145
  /// Register a closure to be called when the object changes.
146
  ///
147 148 149 150
  /// 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.
  ///
151
  /// This method must not be called after [dispose] has been called.
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
  ///
  /// {@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.
171
  @override
172
  void addListener(VoidCallback listener) {
173
    assert(_debugAssertNotDisposed());
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    if (_count == _listeners.length) {
      if (_count == 0) {
        _listeners = List<VoidCallback?>.filled(1, null);
      } else {
        final List<VoidCallback?> newListeners =
            List<VoidCallback?>.filled(_listeners.length * 2, null);
        for (int i = 0; i < _count; i++) {
          newListeners[i] = _listeners[i];
        }
        _listeners = newListeners;
      }
    }
    _listeners[_count++] = listener;
  }

  void _removeAt(int index) {
    // The list holding the listeners is not growable for performances reasons.
    // We still want to shrink this list if a lot of listeners have been added
    // and then removed outside a notifyListeners iteration.
    // We do this only when the real number of listeners is half the length
    // of our list.
    _count -= 1;
    if (_count * 2 <= _listeners.length) {
      final List<VoidCallback?> newListeners = List<VoidCallback?>.filled(_count, null);

      // Listeners before the index are at the same place.
      for (int i = 0; i < index; i++)
        newListeners[i] = _listeners[i];

      // Listeners after the index move towards the start of the list.
      for (int i = index; i < _count; i++)
        newListeners[i] = _listeners[i + 1];

      _listeners = newListeners;
    } else {
      // When there are more listeners than half the length of the list, we only
      // shift our listeners, so that we avoid to reallocate memory for the
      // whole list.
      for (int i = index; i < _count; i++)
        _listeners[i] = _listeners[i + 1];
      _listeners[_count] = null;
    }
216 217 218 219
  }

  /// Remove a previously registered closure from the list of closures that are
  /// notified when the object changes.
220 221 222 223
  ///
  /// If the given listener is not registered, the call is ignored.
  ///
  /// This method must not be called after [dispose] has been called.
224
  ///
225
  /// {@macro flutter.foundation.ChangeNotifier.addListener}
226
  ///
227 228 229 230
  /// See also:
  ///
  ///  * [addListener], which registers a closure to be called when the object
  ///    changes.
231
  @override
232
  void removeListener(VoidCallback listener) {
233
    assert(_debugAssertNotDisposed());
234
    for (int i = 0; i < _count; i++) {
235 236
      final VoidCallback? listenerAtIndex = _listeners[i];
      if (listenerAtIndex == listener) {
237 238 239 240 241 242 243 244 245 246 247 248 249
        if (_notificationCallStackDepth > 0) {
          // We don't resize the list during notifyListeners iterations
          // but we set to null, the listeners we want to remove. We will
          // effectively resize the list at the end of all notifyListeners
          // iterations.
          _listeners[i] = null;
          _reentrantlyRemovedListeners++;
        } else {
          // When we are outside the notifyListeners iterations we can
          // effectively shrink the list.
          _removeAt(i);
        }
        break;
250 251
      }
    }
252 253
  }

254 255 256 257
  /// 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).
258 259 260 261
  ///
  /// This method should only be called by the object's owner.
  @mustCallSuper
  void dispose() {
262
    assert(_debugAssertNotDisposed());
263 264 265 266
    assert(() {
      _debugDisposed = true;
      return true;
    }());
267 268 269 270 271
  }

  /// Call all the registered listeners.
  ///
  /// Call this method whenever the object changes, to notify any clients the
272 273 274
  /// 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.
275 276 277
  ///
  /// Exceptions thrown by listeners will be caught and reported using
  /// [FlutterError.reportError].
278 279
  ///
  /// This method must not be called after [dispose] has been called.
280
  ///
281
  /// Surprising behavior can result when reentrantly removing a listener (e.g.
282 283
  /// in response to a notification) that has been registered multiple times.
  /// See the discussion at [removeListener].
284
  @protected
285
  @visibleForTesting
286
  @pragma('vm:notify-debugger-on-exception')
287
  void notifyListeners() {
288
    assert(_debugAssertNotDisposed());
289
    if (_count == 0)
290 291
      return;

292 293 294 295 296 297 298 299 300 301
    // To make sure that listeners removed during this iteration are not called,
    // we set them to null, but we don't shrink the list right away.
    // By doing this, we can continue to iterate on our list until it reaches
    // the last listener added before the call to this method.

    // To allow potential listeners to recursively call notifyListener, we track
    // the number of times this method is called in _notificationCallStackDepth.
    // Once every recursive iteration is finished (i.e. when _notificationCallStackDepth == 0),
    // we can safely shrink our list so that it will only contain not null
    // listeners.
302

303 304 305 306
    _notificationCallStackDepth++;

    final int end = _count;
    for (int i = 0; i < end; i++) {
307
      try {
308
        _listeners[i]?.call();
309 310 311 312 313 314
      } catch (exception, stack) {
        FlutterError.reportError(FlutterErrorDetails(
          exception: exception,
          stack: stack,
          library: 'foundation library',
          context: ErrorDescription('while dispatching notifications for $runtimeType'),
315 316
          informationCollector: () => <DiagnosticsNode>[
            DiagnosticsProperty<ChangeNotifier>(
317 318 319
              'The $runtimeType sending notification was',
              this,
              style: DiagnosticsTreeStyle.errorProperty,
320 321
            ),
          ],
322
        ));
323 324
      }
    }
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

    _notificationCallStackDepth--;

    if (_notificationCallStackDepth == 0 && _reentrantlyRemovedListeners > 0) {
      // We really remove the listeners when all notifications are done.
      final int newLength = _count - _reentrantlyRemovedListeners;
      if (newLength * 2 <= _listeners.length) {
        // As in _removeAt, we only shrink the list when the real number of
        // listeners is half the length of our list.
        final List<VoidCallback?> newListeners = List<VoidCallback?>.filled(newLength, null);

        int newIndex = 0;
        for (int i = 0; i < _count; i++) {
          final VoidCallback? listener = _listeners[i];
          if (listener != null) {
            newListeners[newIndex++] = listener;
          }
        }

        _listeners = newListeners;
      } else {
        // Otherwise we put all the null references at the end.
        for (int i = 0; i < newLength; i += 1) {
          if (_listeners[i] == null) {
            // We swap this item with the next not null item.
            int swapIndex = i + 1;
351
            while(_listeners[swapIndex] == null) {
352 353 354 355 356 357 358 359 360 361 362
              swapIndex += 1;
            }
            _listeners[i] = _listeners[swapIndex];
            _listeners[swapIndex] = null;
          }
        }
      }

      _reentrantlyRemovedListeners = 0;
      _count = newLength;
    }
363 364
  }
}
Ian Hickson's avatar
Ian Hickson committed
365

366 367
class _MergingListenable extends Listenable {
  _MergingListenable(this._children);
Ian Hickson's avatar
Ian Hickson committed
368

369
  final List<Listenable?> _children;
Ian Hickson's avatar
Ian Hickson committed
370 371

  @override
372
  void addListener(VoidCallback listener) {
373
    for (final Listenable? child in _children) {
374 375 376 377 378 379
      child?.addListener(listener);
    }
  }

  @override
  void removeListener(VoidCallback listener) {
380
    for (final Listenable? child in _children) {
381 382
      child?.removeListener(listener);
    }
Ian Hickson's avatar
Ian Hickson committed
383
  }
384 385 386

  @override
  String toString() {
387
    return 'Listenable.merge([${_children.join(", ")}])';
388
  }
Ian Hickson's avatar
Ian Hickson committed
389
}
Adam Barth's avatar
Adam Barth committed
390 391 392

/// A [ChangeNotifier] that holds a single value.
///
393 394 395
/// 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.
396
class ValueNotifier<T> extends ChangeNotifier implements ValueListenable<T> {
Adam Barth's avatar
Adam Barth committed
397 398 399 400 401
  /// Creates a [ChangeNotifier] that wraps this value.
  ValueNotifier(this._value);

  /// The current value stored in this notifier.
  ///
402 403 404
  /// 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.
405
  @override
Adam Barth's avatar
Adam Barth committed
406 407 408 409 410 411 412 413
  T get value => _value;
  T _value;
  set value(T newValue) {
    if (_value == newValue)
      return;
    _value = newValue;
    notifyListeners();
  }
414 415

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