when<R> method
R
when<R>({
- required R data(
- T data
- required R loading(),
- required R error(
- Object error,
- StackTrace stackTrace
- bool skipLoading = true,
- 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),
},
};
}