W3cubDocs

/Dart 2

Future<T>.sync constructor

Future<T>.sync(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.

Implementation

factory Future.sync(FutureOr<T> computation()) {
  try {
    var result = computation();
    if (result is Future<T>) {
      return result;
    } else {
      return new _Future<T>.value(result);
    }
  } catch (error, stackTrace) {
    var future = new _Future<T>();
    AsyncError replacement = Zone.current.errorCallback(error, stackTrace);
    if (replacement != null) {
      future._asyncCompleteError(
          _nonNullError(replacement.error), replacement.stackTrace);
    } else {
      future._asyncCompleteError(error, stackTrace);
    }
    return future;
  }
}

© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dart.dev/stable/2.5.0/dart-async/Future/Future.sync.html