onDispose abstract method
void
onDispose(
- void cb()
inherited
Adds a listener to perform an operation right before the provider is destroyed.
This includes:
- when the provider will rebuild (such as when using
watchorrefresh). - when an
autoDisposeprovider is no longer used - when the associated
ProviderContainer/ProviderScopeis disposed`.
Prefer having multiple onDispose, for every disposable object created,
instead of a single large onDispose:
Good:
final disposable1 = Disposable(...);
ref.onDispose(disposable1.dispose);
final disposable2 = Disposable(...);
ref.onDispose(disposable2.dispose);
Bad:
final disposable1 = Disposable(...);
final disposable2 = Disposable(...);
ref.onDispose(() {
disposable1.dispose();
disposable2.dispose();
});
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
disposecall 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 beforeonDisposeis called, then some of your objects may not be disposed.
See also:
Provider.autoDispose, a modifier which tell a provider that it should destroy its state when no longer listened to.ProviderContainer.dispose, to destroy all providers associated with aProviderContainerat once.onCancel, a life-cycle for when all listeners of a provider are removed.
Implementation
void onDispose(void Function() cb);