AsyncValue<T>.from constructor

AsyncValue<T>.from(
  1. Object? value
)

Creates an instance from value:

  • A Future.
  • A function returning a Future or a value (called in a microtask).

A Future (or function) declared with a type other than T (such as a Future<dynamic>) is accepted: its result is cast to T, and if it isn't a T, the future completes with a TypeError (see error).

Implementation

factory AsyncValue.from(Object? value) {
  if (value is Future) {
    return AsyncValue<T>(_asFutureOfT<T>(value));
  } else if (value is Future<T> Function()) {
    var future = value();
    return AsyncValue<T>(future);
  } else if (value is Future Function()) {
    var future = value();
    return AsyncValue<T>(_asFutureOfT<T>(future));
  } else if (value is T Function()) {
    var future = Future.microtask(() => value());
    return AsyncValue<T>(future);
  } else if (value is Function) {
    // A function with another declared return type (such as `dynamic`,
    // `Object` or `FutureOr<T>`): its result must be a `T` (or a `Future`
    // of a `T`).
    var future = Future<T>.microtask(() async {
      var result = value();
      if (result is Future) {
        result = await result;
      }
      return result as T;
    });
    return AsyncValue<T>(future);
  } else {
    throw ArgumentError('Not an async value: $value');
  }
}