dispose method

  1. @override
  2. @mustCallSuper
void dispose()
inherited

The framework calls this method when this StateX object will never build again and will be disposed of with garbage collection.

Implementation

@override
@mustCallSuper
void dispose() {
  // **IMPORTANT** Call super.dispose() below instead
  /// The State object's lifecycle is terminated.
  /// **IMPORTANT** You will not know when this will run
  /// It's to the Flutter engines discretion. deactivate() is more reliable.
  /// Subclasses should override deactivate() method instead
  /// to release any resources  (e.g., stop any active animations).
  try {
    // runZonedGuarded<void>(() {
    // scheduleMicrotask(() {
    // Remove from the list of StateX objects present in the app!
    // It may be premature but Controllers still have access.
    _removeFromMapOfStates(this);

    // If 'AppState' is not used
    if (appStateX == null) {
      // Unregisters the given observer.
      WidgetsBinding.instance.removeObserver(this);
    }

    /// Users may have explicitly call this.
    if (_disposed || !_deactivated) {
      assert(() {
        debugPrint('StateX: dispose() already called in $this');
        return true;
      }());
      return;
    }

    /// Indicate this State object is terminated.
    _disposed = true;

    // No 'setState()' functions are allowed to fully function at this point.
    _setStateAllowed = false;

    /// Call its controllers' dispose() functions
    for (final con in controllerList) {
      con.disposeState(this);
      if (con.lastState == null) {
        con.dispose();
      }
    }

    // Remove any 'StateXController' reference
    _controller = null;

    // Remove App State object
    _appStateX = null;

    // In some cases, the setState() will be called again! gp
    _setStateAllowed = true;

    // In some cases, if then reinserted back in another part of the tree
    // the build is called, and so setState() is not necessary.
    _setStateRequested = false; // Special case: Test if already disposed

    if (mounted) {
      super.dispose();
      assert(() {
        if (_debugPrintEvents) {
          debugPrint('$_consoleLeadingLine dispose() in $this');
        }
        return true;
      }());
    } else {
      assert(() {
        debugPrint('StateX: Not mounted so dispose() not called in $this');
        return true;
      }());
    }
    // });
    // }, (error, stackTrace) {
  } catch (e) {
    _logPackageError(
      e,
      library: 'part01_statex.dart',
      description: 'Error in dispose()',
    );
    // });
  }
}