onDispose method

  1. @override
  2. @protected
void onDispose()
override

Called during the disposal process to perform custom cleanup.

This method is automatically invoked by the framework's disposal mechanism as part of the disposal flow. It's called after the disposed flag is set but before attached resources are disposed and pending values are cleared. This provides a clean way to add custom cleanup logic without worrying about idempotency concerns, as the framework handles the complexity of ensuring dispose is idempotent.

Key Benefits:

  • No need to worry about idempotency - the framework handles it
  • Can be safely overridden multiple times in inheritance chains
  • Focus purely on cleanup logic without disposal state management
  • Automatic integration with the disposal framework

Execution Flow: The disposal process follows this general pattern:

@override
@mustCallSuper
void dispose() {
  if (isDisposed) return;        // 1. Idempotency check
  isDisposed = true;             // 2. Set disposed flag
  onDispose();                   // 3. Custom cleanup (this method)
  ...                            // 4. Additional cleanup as needed
}

Implementation Notes:

  • This method is optional and has a default empty implementation
  • Can be either synchronous or asynchronous
  • Called automatically by the framework - don't call directly
  • Exceptions should be handled gracefully to not break the disposal chain

Example:

@override
Future<void> onDispose() async {
  // Focus on cleanup logic only - no idempotency concerns
  await _cleanupCustomResources();
  _notifyDisposalListeners();
  _closeConnections();
}

Implementation

@override
@protected
void onDispose() {
  doCleanup();
  disposeNode(this);
}