onWillDispose method

  1. @mustCallSuper
  2. @override
  3. @protected
Future<Null> onWillDispose()

Callback to allow arbitrary cleanup as soon as disposal is requested (i.e. dispose is called) but prior to disposal actually starting.

Disposal will not start before the Future returned from this method completes.

Implementation

@mustCallSuper
@override
@protected
Future<Null> onWillDispose() async {
  if (isInstantiated || isUnloaded) {
    return;
  }

  try {
    Future<Null> unloadingTransitionFuture;
    if (isUnloading) {
      unloadingTransitionFuture = _transition!.future;
    } else {
      Future? pendingTransition;
      if (_transition != null && !_transition!.isCompleted) {
        pendingTransition = _transition?.future;
      }
      _previousState = _state;
      _state = LifecycleState.unloading;
      unloadingTransitionFuture =
          _unload(pendingTransition?.then((value) => value as Null));
    }
    await unloadingTransitionFuture;
  } on ModuleUnloadCanceledException {
    // The unload was canceled, but disposal cannot be canceled. Log a warning
    // indicating this and continue with disposal.
    _logger.warning(
        '.dispose() was called but Module "$name" canceled its '
        'unload. The module will still be disposed.',
        null,
        StackTrace.current);
  } catch (error, stackTrace) {
    // An unexpected exception was thrown during unload. It will be emitted
    // as an error on the didUnload stream, but we will also log a warning
    // here explaining that disposal will still continue.
    _logger.warning(
        '.dispose() was called but Module "$name" threw an exception on '
        'unload. The module will still be disposed.',
        error,
        stackTrace);
  }
}