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

import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';

import 'framework.dart';

export 'package:flutter/scheduler.dart' show TickerProvider;

12 13 14
// Examples can assume:
// late BuildContext context;

15 16 17 18 19 20
/// Enables or disables tickers (and thus animation controllers) in the widget
/// subtree.
///
/// This only works if [AnimationController] objects are created using
/// widget-aware ticker providers. For example, using a
/// [TickerProviderStateMixin] or a [SingleTickerProviderStateMixin].
21
class TickerMode extends StatefulWidget {
22 23 24
  /// Creates a widget that enables or disables tickers.
  ///
  /// The [enabled] argument must not be null.
25
  const TickerMode({
26
    super.key,
27 28
    required this.enabled,
    required this.child,
29
  }) : assert(enabled != null);
30

31 32 33 34
  /// The requested ticker mode for this subtree.
  ///
  /// The effective ticker mode of this subtree may differ from this value
  /// if there is an ancestor [TickerMode] with this field set to false.
35
  ///
36 37
  /// If true and all ancestor [TickerMode]s are also enabled, then tickers in
  /// this subtree will tick.
38
  ///
39 40 41
  /// If false, then tickers in this subtree will not tick regardless of any
  /// ancestor [TickerMode]s. Animations driven by such tickers are not paused,
  /// they just don't call their callbacks. Time still elapses.
42 43
  final bool enabled;

44 45
  /// The widget below this widget in the tree.
  ///
46
  /// {@macro flutter.widgets.ProxyWidget.child}
47 48
  final Widget child;

49 50 51 52 53 54 55
  /// Whether tickers in the given subtree should be enabled or disabled.
  ///
  /// This is used automatically by [TickerProviderStateMixin] and
  /// [SingleTickerProviderStateMixin] to decide if their tickers should be
  /// enabled or disabled.
  ///
  /// In the absence of a [TickerMode] widget, this function defaults to true.
56 57 58 59 60 61
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// bool tickingEnabled = TickerMode.of(context);
  /// ```
62
  static bool of(BuildContext context) {
63
    final _EffectiveTickerMode? widget = context.dependOnInheritedWidgetOfExactType<_EffectiveTickerMode>();
64 65 66
    return widget?.enabled ?? true;
  }

67 68 69 70 71 72 73 74 75 76 77
  /// Obtains a [ValueNotifier] from the [TickerMode] surrounding the `context`,
  /// which indicates whether tickers are enabled in the given subtree.
  ///
  /// When that [TickerMode] enabled or disabled tickers, the notifier notifies
  /// its listeners.
  ///
  /// While the [ValueNotifier] is stable for the lifetime of the surrounding
  /// [TickerMode], calling this method does not establish a dependency between
  /// the `context` and the [TickerMode] and the widget owning the `context`
  /// does not rebuild when the ticker mode changes from true to false or vice
  /// versa. This is preferable when the ticker mode does not impact what is
78
  /// currently rendered on screen, e.g. because it is only used to mute/unmute a
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  /// [Ticker]. Since no dependency is established, the widget owning the
  /// `context` is also not informed when it is moved to a new location in the
  /// tree where it may have a different [TickerMode] ancestor. When this
  /// happens, the widget must manually unsubscribe from the old notifier,
  /// obtain a new one from the new ancestor [TickerMode] by calling this method
  /// again, and re-subscribe to it. [StatefulWidget]s can, for example, do this
  /// in [State.activate], which is called after the widget has been moved to
  /// a new location.
  ///
  /// Alternatively, [of] can be used instead of this method to create a
  /// dependency between the provided `context` and the ancestor [TickerMode].
  /// In this case, the widget automatically rebuilds when the ticker mode
  /// changes or when it is moved to a new [TickerMode] ancestor, which
  /// simplifies the management cost in the widget at the expensive of some
  /// potential unnecessary rebuilds.
  ///
  /// In the absence of a [TickerMode] widget, this function returns a
  /// [ValueNotifier], whose [ValueNotifier.value] is always true.
  static ValueNotifier<bool> getNotifier(BuildContext context) {
    final _EffectiveTickerMode? widget = context.getElementForInheritedWidgetOfExactType<_EffectiveTickerMode>()?.widget as _EffectiveTickerMode?;
    return widget?.notifier ?? ValueNotifier<bool>(true);
  }

  @override
  State<TickerMode> createState() => _TickerModeState();
}

class _TickerModeState extends State<TickerMode> {
  bool _ancestorTicketMode = true;
  final ValueNotifier<bool> _effectiveMode = ValueNotifier<bool>(true);

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _ancestorTicketMode = TickerMode.of(context);
    _updateEffectiveMode();
  }

  @override
  void didUpdateWidget(TickerMode oldWidget) {
    super.didUpdateWidget(oldWidget);
    _updateEffectiveMode();
  }

  @override
  void dispose() {
    _effectiveMode.dispose();
    super.dispose();
  }

  void _updateEffectiveMode() {
    _effectiveMode.value = _ancestorTicketMode && widget.enabled;
  }

133
  @override
134 135
  Widget build(BuildContext context) {
    return _EffectiveTickerMode(
136 137 138
      enabled: _effectiveMode.value,
      notifier: _effectiveMode,
      child: widget.child,
139 140 141 142 143 144
    );
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
145
    properties.add(FlagProperty('requested mode', value: widget.enabled, ifTrue: 'enabled', ifFalse: 'disabled', showName: true));
146 147 148 149 150
  }
}

class _EffectiveTickerMode extends InheritedWidget {
  const _EffectiveTickerMode({
151
    required this.enabled,
152
    required this.notifier,
153 154
    required super.child,
  }) : assert(enabled != null);
155 156

  final bool enabled;
157
  final ValueNotifier<bool> notifier;
158 159 160

  @override
  bool updateShouldNotify(_EffectiveTickerMode oldWidget) => enabled != oldWidget.enabled;
161 162

  @override
163 164
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
165
    properties.add(FlagProperty('effective mode', value: enabled, ifTrue: 'enabled', ifFalse: 'disabled', showName: true));
166 167 168 169 170 171 172 173 174 175 176 177 178
  }
}

/// Provides a single [Ticker] that is configured to only tick while the current
/// tree is enabled, as defined by [TickerMode].
///
/// To create the [AnimationController] in a [State] that only uses a single
/// [AnimationController], mix in this class, then pass `vsync: this`
/// to the animation controller constructor.
///
/// This mixin only supports vending a single ticker. If you might have multiple
/// [AnimationController] objects over the lifetime of the [State], use a full
/// [TickerProviderStateMixin] instead.
179
@optionalTypeArgs
180
mixin SingleTickerProviderStateMixin<T extends StatefulWidget> on State<T> implements TickerProvider {
181
  Ticker? _ticker;
182 183 184 185

  @override
  Ticker createTicker(TickerCallback onTick) {
    assert(() {
186
      if (_ticker == null) {
187
        return true;
188
      }
189 190 191 192 193 194
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('$runtimeType is a SingleTickerProviderStateMixin but multiple tickers were created.'),
        ErrorDescription('A SingleTickerProviderStateMixin can only be used as a TickerProvider once.'),
        ErrorHint(
          'If a State is used for multiple AnimationController objects, or if it is passed to other '
          'objects and those objects might use it more than one time in total, then instead of '
195 196
          'mixing in a SingleTickerProviderStateMixin, use a regular TickerProviderStateMixin.',
        ),
197
      ]);
198
    }());
199
    _ticker = Ticker(onTick, debugLabel: kDebugMode ? 'created by ${describeIdentity(this)}' : null);
200 201
    _updateTickerModeNotifier();
    _updateTicker(); // Sets _ticker.mute correctly.
202
    return _ticker!;
203 204 205 206 207
  }

  @override
  void dispose() {
    assert(() {
208
      if (_ticker == null || !_ticker!.isActive) {
209
        return true;
210
      }
211 212 213 214 215
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('$this was disposed with an active Ticker.'),
        ErrorDescription(
          '$runtimeType created a Ticker via its SingleTickerProviderStateMixin, but at the time '
          'dispose() was called on the mixin, that Ticker was still active. The Ticker must '
216
          'be disposed before calling super.dispose().',
217 218 219 220
        ),
        ErrorHint(
          'Tickers used by AnimationControllers '
          'should be disposed by calling dispose() on the AnimationController itself. '
221
          'Otherwise, the ticker will leak.',
222
        ),
223
        _ticker!.describeForError('The offending ticker was'),
224
      ]);
225
    }());
226 227
    _tickerModeNotifier?.removeListener(_updateTicker);
    _tickerModeNotifier = null;
228 229 230
    super.dispose();
  }

231 232
  ValueNotifier<bool>? _tickerModeNotifier;

233
  @override
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  void activate() {
    super.activate();
    // We may have a new TickerMode ancestor.
    _updateTickerModeNotifier();
    _updateTicker();
  }

  void _updateTicker() {
    if (_ticker != null) {
      _ticker!.muted = !_tickerModeNotifier!.value;
    }
  }

  void _updateTickerModeNotifier() {
    final ValueNotifier<bool> newNotifier = TickerMode.getNotifier(context);
    if (newNotifier == _tickerModeNotifier) {
      return;
    }
    _tickerModeNotifier?.removeListener(_updateTicker);
    newNotifier.addListener(_updateTicker);
    _tickerModeNotifier = newNotifier;
255 256 257
  }

  @override
258 259
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
260
    String? tickerDescription;
261
    if (_ticker != null) {
262
      if (_ticker!.isActive && _ticker!.muted) {
263
        tickerDescription = 'active but muted';
264
      } else if (_ticker!.isActive) {
265
        tickerDescription = 'active';
266
      } else if (_ticker!.muted) {
267
        tickerDescription = 'inactive and muted';
268
      } else {
269
        tickerDescription = 'inactive';
270
      }
271
    }
272
    properties.add(DiagnosticsProperty<Ticker>('ticker', _ticker, description: tickerDescription, showSeparator: false, defaultValue: null));
273 274 275 276 277 278 279 280 281 282 283 284 285
  }
}

/// Provides [Ticker] objects that are configured to only tick while the current
/// tree is enabled, as defined by [TickerMode].
///
/// To create an [AnimationController] in a class that uses this mixin, pass
/// `vsync: this` to the animation controller constructor whenever you
/// create a new animation controller.
///
/// If you only have a single [Ticker] (for example only a single
/// [AnimationController]) for the lifetime of your [State], then using a
/// [SingleTickerProviderStateMixin] is more efficient. This is the common case.
286
@optionalTypeArgs
287
mixin TickerProviderStateMixin<T extends StatefulWidget> on State<T> implements TickerProvider {
288
  Set<Ticker>? _tickers;
289 290 291

  @override
  Ticker createTicker(TickerCallback onTick) {
292 293 294 295 296
    if (_tickerModeNotifier == null) {
      // Setup TickerMode notifier before we vend the first ticker.
      _updateTickerModeNotifier();
    }
    assert(_tickerModeNotifier != null);
297
    _tickers ??= <_WidgetTicker>{};
298 299
    final _WidgetTicker result = _WidgetTicker(onTick, this, debugLabel: kDebugMode ? 'created by ${describeIdentity(this)}' : null)
      ..muted = !_tickerModeNotifier!.value;
300
    _tickers!.add(result);
301 302 303 304 305
    return result;
  }

  void _removeTicker(_WidgetTicker ticker) {
    assert(_tickers != null);
306 307
    assert(_tickers!.contains(ticker));
    _tickers!.remove(ticker);
308 309
  }

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
  ValueNotifier<bool>? _tickerModeNotifier;

  @override
  void activate() {
    super.activate();
    // We may have a new TickerMode ancestor, get its Notifier.
    _updateTickerModeNotifier();
    _updateTickers();
  }

  void _updateTickers() {
    if (_tickers != null) {
      final bool muted = !_tickerModeNotifier!.value;
      for (final Ticker ticker in _tickers!) {
        ticker.muted = muted;
      }
    }
  }

  void _updateTickerModeNotifier() {
    final ValueNotifier<bool> newNotifier = TickerMode.getNotifier(context);
    if (newNotifier == _tickerModeNotifier) {
      return;
    }
    _tickerModeNotifier?.removeListener(_updateTickers);
    newNotifier.addListener(_updateTickers);
    _tickerModeNotifier = newNotifier;
  }

339 340 341 342
  @override
  void dispose() {
    assert(() {
      if (_tickers != null) {
343
        for (final Ticker ticker in _tickers!) {
344
          if (ticker.isActive) {
345 346 347 348 349
            throw FlutterError.fromParts(<DiagnosticsNode>[
              ErrorSummary('$this was disposed with an active Ticker.'),
              ErrorDescription(
                '$runtimeType created a Ticker via its TickerProviderStateMixin, but at the time '
                'dispose() was called on the mixin, that Ticker was still active. All Tickers must '
350
                'be disposed before calling super.dispose().',
351 352 353 354
              ),
              ErrorHint(
                'Tickers used by AnimationControllers '
                'should be disposed by calling dispose() on the AnimationController itself. '
355
                'Otherwise, the ticker will leak.',
356 357 358
              ),
              ticker.describeForError('The offending ticker was'),
            ]);
359 360 361 362
          }
        }
      }
      return true;
363
    }());
364 365
    _tickerModeNotifier?.removeListener(_updateTickers);
    _tickerModeNotifier = null;
366 367 368 369
    super.dispose();
  }

  @override
370 371
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
372
    properties.add(DiagnosticsProperty<Set<Ticker>>(
373 374 375
      'tickers',
      _tickers,
      description: _tickers != null ?
376
        'tracking ${_tickers!.length} ticker${_tickers!.length == 1 ? "" : "s"}' :
377 378 379
        null,
      defaultValue: null,
    ));
380 381 382 383 384 385 386 387
  }
}

// This class should really be called _DisposingTicker or some such, but this
// class name leaks into stack traces and error messages and that name would be
// confusing. Instead we use the less precise but more anodyne "_WidgetTicker",
// which attracts less attention.
class _WidgetTicker extends Ticker {
388
  _WidgetTicker(super.onTick, this._creator, { super.debugLabel });
389

390
  final TickerProviderStateMixin _creator;
391 392 393 394 395 396 397

  @override
  void dispose() {
    _creator._removeTicker(this);
    super.dispose();
  }
}