when<R> method

R when<R>({
  1. required R data(
    1. T data
    ),
  2. required R loading(),
  3. required R error(
    1. Object error,
    2. StackTrace stackTrace
    ),
  4. bool skipLoading = true,
  5. bool skipError = false,
})

Syntactic sugar for AsyncValue. If skipLoading is true and there is previous data, the result of data will be returned instead of loading. If skipError is true and there is previous data, the result of data will be returned instead of error.

Usage: final futureProvider = FutureProvider((ref) async { final response = await ref.read(apiProvider).get(); return response.data; });

// ...

final futureState = ref.watch(futureProvider);

futureState.when( data: (data) => Text(data), loading: () => const CircularProgressIndicator(), error: (error, stackTrace) => Text(error.toString()), );

Implementation

R when<R>({
  required R Function(T data) data,
  required R Function() loading,
  required R Function(Object error, StackTrace stackTrace) error,
  bool skipLoading = true,
  bool skipError = false,
}) {
  return switch (this) {
    AsyncData<T> curr => data(curr.data),
    AsyncLoading<T> curr => switch (curr.data) {
        T t when skipLoading => data(t),
        _ => loading()
      },
    AsyncError<T> curr => switch (curr.data) {
        T t when skipError => data(t),
        _ => error(curr.error, curr.stackTrace),
      },
  };
}