watchFuture<T extends Object, R> function

AsyncSnapshot<R> watchFuture<T extends Object, R>(
  1. Future<R> select(
    1. T
    )?, {
  2. T? target,
  3. required R initialValue,
  4. String? instanceName,
  5. bool preserveState = true,
  6. bool allowFutureChange = false,
  7. GetIt? getIt,
})

watchFuture observes the Future returned by select and triggers a rebuild as soon as this Future completes. After that it returns an AsyncSnapshot with the received data from the Future When you call watchFuture a second time on the same Future it will return the last received data but not observe the Future a another time. To be able to use watchFuture inside a build function we have to pass initialValue so that it can return something before the Future has completed if select returns a different Future than on the last call, watchFuture will ignore the completion of the previous Future and observe the completion of the new Future. preserveState determines then if the new initial value should be the last value of the previous Future or again initialValue If you want to observe a Future that is not registered in get_it you can pass it as target. if you pass null as select, T or target has to be a Future<R>. instanceName is the optional name of the instance if you registered it with a name in get_it.

getIt is the optional instance of get_it to use if you don't want to use the default one. 99% of the time you won't need this.

Implementation

AsyncSnapshot<R> watchFuture<T extends Object, R>(
  Future<R> Function(T)? select, {
  T? target,
  required R initialValue,
  String? instanceName,
  bool preserveState = true,
  bool allowFutureChange = false,
  GetIt? getIt,
}) {
  assert(_activeWatchItState != null,
      'watchFuture can only be called inside a build function within a WatchingWidget or a widget using the WatchItMixin');

  final getItInstance = getIt ?? di;
  final parentObject = target ?? getItInstance<T>(instanceName: instanceName);

  // Validate target type when no select function is provided
  if (select == null && parentObject is! Future<R>) {
    throw ArgumentError(
        'When no select function is provided, target must be a Future<$R>. '
        'Got: ${parentObject.runtimeType}');
  }

  return _activeWatchItState!.registerFutureHandler<T, R>(
      parentOrFuture: parentObject,
      initialValueProvider: () => initialValue,
      instanceName: instanceName,
      preserveState: preserveState,
      allowMultipleSubscribers: false,
      selector: select,
      allowFutureChange: allowFutureChange);
}