Future<T>.sync constructor

Future<T>.sync(
  1. FutureOr<T> computation()
)

Returns a future containing the result of immediately calling computation.

If calling computation throws, the returned future is completed with the error.

If calling computation returns a Future<T>, that future is returned.

If calling computation returns a non-future value, a future is returned which has been completed with that value.

Example:

final result = await Future<int>.sync(() => 12);

Implementation

factory Future.sync(FutureOr<T> computation()) {
  FutureOr<T> result;
  try {
    result = computation();
  } catch (error, stackTrace) {
    var future = new _Future<T>();
    _asyncCompleteWithErrorCallback(future, error, stackTrace);
    return future;
  }
  return result is Future<T> ? result : _Future<T>.value(result);
}