onDispose abstract method

void onDispose(
  1. void cb()

Adds a listener to perform an operation right before the provider is destroyed.

This includes:

  • when the provider will rebuild (such as when using watch or refresh).
  • when an autoDispose provider is no longer used
  • when the associated ProviderContainer/ProviderScope is disposed`.

Prefer having multiple onDispose, for every disposable object created, instead of a single large onDispose:


final disposable1 = Disposable(...);

final disposable2 = Disposable(...);


final disposable1 = Disposable(...);
final disposable2 = Disposable(...);

ref.onDispose(() {

This is preferable for multiple reasons:

  • It is easier for readers to know if a "dispose" is missing for a given object. That is because the dispose call is directly next to the object creation.
  • It prevents memory leaks in cases of an exception. If an exception happens inside a dispose() call, or if an exception happens before onDispose is called, then some of your objects may not be disposed.

See also:


void onDispose(void Function() cb);