withDefer<T> function

T withDefer<T>(
  1. T run(
    1. void defer(
      1. void callback()
      )
    )
)

Implementation

T withDefer<T>(T Function(void Function(void Function() callback) defer) run) {
  final deferred = <void Function()>[];
  defer(void Function() callback) {
    deferred.add(callback);
  }

  final result = run(defer);
  for (final callback in deferred) {
    callback();
  }
  return result;
}