addCleanup method
- @protected
Puts a registration on the cleanup stack of the owner.
The public onDispose and onDiscard are this with value unset;
abandonable, join and run pass the value they hand to the body, so
that disown can find the registration by it.
Implementation
@protected
void Function() addCleanup(
FutureOr<void> Function() disposer, {
required bool always,
Object? value,
}) {
if (_owner.isFinished) {
throw StateError(
'$_owner has already finished, cannot register a cleanup',
);
}
final cleanup = _Cleanup(
disposer,
always: always,
order: _owner._cleanupOrder++,
owner: _owner,
value: value,
);
_owner._cleanups.add(cleanup);
// Held in a variable and reached through the registration, not through
// this context: the caller may keep the remover until its own end, and
// it must not keep the disposer or the job — see [_Cleanup.release].
_Cleanup? held = cleanup;
return () {
final cleanup = held;
held = null;
// Null once the registration has run or been dropped.
final owner = cleanup?.owner;
if (cleanup == null || owner == null) return;
// Both lists: the unwinding moves a registration it decided to put off
// out of the stack, and a disposer running below it may still take
// that one back.
owner._cleanups.remove(cleanup);
owner._skipped.remove(cleanup);
};
}