dispose method Null safety

  1. @override
void dispose()
override

Called when this object is removed from the tree permanently.

The framework calls this method when this State object will never build again. After the framework calls dispose, the State object is considered unmounted and the mounted property is false. It is an error to call setState at this point. This stage of the lifecycle is terminal: there is no way to remount a State object that has been disposed.

Subclasses should override this method to release any resources retained by this object (e.g., stop any active animations).

If a State's build method depends on an object that can itself change state, for example a ChangeNotifier or Stream, or some other object to which one can subscribe to receive notifications, then be sure to subscribe and unsubscribe properly in initState, didUpdateWidget, and dispose:

  • In initState, subscribe to the object.
  • In didUpdateWidget unsubscribe from the old object and subscribe to the new one if the updated widget configuration requires replacing the object.
  • In dispose, unsubscribe from the object.

Implementations of this method should end with a call to the inherited method, as in super.dispose().

See also:

Implementation

@override
void dispose() {
  assert(() {
    if (_tickers != null) {
      for (final Ticker ticker in _tickers!) {
        if (ticker.isActive) {
          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 '
              'be disposed before calling super.dispose().',
            ),
            ErrorHint(
              'Tickers used by AnimationControllers '
              'should be disposed by calling dispose() on the AnimationController itself. '
              'Otherwise, the ticker will leak.',
            ),
            ticker.describeForError('The offending ticker was'),
          ]);
        }
      }
    }
    return true;
  }());
  _tickerModeNotifier?.removeListener(_updateTickers);
  _tickerModeNotifier = null;
  super.dispose();
}