Future<T>.delayed constructor

Future<T>.delayed(
  1. Duration duration, [
  2. FutureOr<T> computation()?
])

Creates a future that runs its computation after a delay.

The computation will be executed after the given duration has passed, and the future is completed with the result of the computation.

If computation returns a future, the future returned by this constructor will complete with the value or error of that future, which may not be available until even later.

If the duration is 0 or less, it completes no sooner than in the next event-loop iteration, after all microtasks have run. (The waiting for the delay uses a Timer created in the current zone.)

The computation must not be omitted, and must not be null. Use Future.pause instead if you just want to wait for duration. Until that is reflected in the signature, if computation is omitted, then T must be nullable. Then the computation will be treated as if it was () => null, and the future will eventually complete with the null value.

If calling computation throws, the created future will complete with the error.

See also Completer for a way to create and complete a future at a later time that isn't necessarily after a known fixed duration.

Example:

var now = DateTime.now();
var later = await Future.delayed(const Duration(seconds: 1), () {
  return DateTime.timestamp();
});
print(now.difference(later)); // At least a second.

Implementation

factory Future.delayed(
  Duration duration, [
  FutureOr<T> Function()? computation,
]) {
  if (computation == null && !typeAcceptsNull<T>()) {
    throw ArgumentError.value(
      null,
      "computation",
      "The type parameter is not nullable",
    );
  }
  _Future<T> result = _Future<T>();
  Timer(duration, () {
    if (computation == null) {
      result._complete(null as T);
    } else {
      FutureOr<T> computationResult;
      try {
        computationResult = computation();
      } catch (e, s) {
        _completeWithErrorCallback(result, e, s);
        return;
      }
      result._complete(computationResult);
    }
  });
  return result;
}