Sub topic 2
AsyncValue: loading, data and error as one value
This chapter looks at AsyncValue, the type Riverpod uses to describe the state of an asynchronous operation. You should already know Dart's Future, async and await, and try/catch. You should also know the basics of Riverpod (Provider, ref.watch, ref.read) and how a Flutter widget's build method works. Dart 3 switch expressions with patterns appear in a few examples, but you can follow the chapter without them.
Why a Future is not enough
A Future<T> describes a computation that will finish once. It is either pending, completed with a value, or completed with an error. That is fine for code that awaits it. It is awkward for a UI that must draw something on every frame.
Suppose a widget holds a Future<List<Todo>>. To render it, you have to wrap it in a FutureBuilder, which creates its own snapshot type. Several problems follow:
- The future is not a value you can read synchronously. You cannot ask "what is the current state?" without awaiting.
- A future never goes back to pending. If you reload, you create a new future, and the old data disappears from view unless you saved it yourself.
- Nothing forces you to handle the error case. An unhandled error in a future can be silently ignored by the UI.
- Other code, such as a test or another provider, cannot easily observe "still loading" as data.
Riverpod solves this by turning the three possible situations into one ordinary value that a provider can expose, replace and notify listeners about. That value is AsyncValue<T>.
The three cases
AsyncValue<T> is a sealed class with three subclasses:
| Subclass | Meaning | What it carries |
|---|---|---|
| `AsyncLoading<T>` | An operation is in progress. | Optionally, a previous value or error. |
| `AsyncData<T>` | The operation finished successfully. | A value of type `T`. |
| `AsyncError<T>` | The operation failed. | An `error` object and a `StackTrace`. |
Because the class is sealed, the compiler knows these are the only cases. A switch over an AsyncValue can be checked for exhaustiveness, so forgetting a case is a compile-time error instead of a blank screen at run time.
You can create each case directly:
import 'package:riverpod/riverpod.dart';
String describe(AsyncValue<int> state) {
return switch (state) {
AsyncData(:final value) => 'data: $value',
AsyncError(:final error) => 'error: $error',
AsyncLoading() => 'loading',
};
}
void main() {
print(describe(const AsyncLoading()));
print(describe(const AsyncData(42)));
print(describe(AsyncError(Exception('boom'), StackTrace.current)));
}Running this prints:
loading
data: 42
error: Exception: boomThe AsyncValue.loading(), AsyncValue.data(42) and AsyncValue.error(error, stackTrace) factory constructors build the same objects. The subclass names are shorter, and you need them anyway as patterns in a switch. Note that AsyncError requires a stack trace. Pass StackTrace.current when you have no better one.
You will rarely create these objects yourself in production code. Riverpod creates them as it runs your provider, and AsyncNotifier (later chapters) lets you assign them to state. Knowing what they contain is still what makes the rest of the API easy to read.
The diagram shows the arrows that matter for UI. Loading is the only state a provider enters from the outside, and it always resolves to data or an error. A reload sends data or an error back to loading, and that is where the "previous value" idea below comes from.
Reading the state without a switch
A switch is not the only way to inspect an AsyncValue. It also exposes boolean flags and nullable accessors:
| Member | Meaning |
|---|---|
| `isLoading` | `true` while the operation is running. |
| `hasValue` | `true` if a value is available, including a previous one. |
| `hasError` | `true` if an error is available. |
| `error` | The error object, or `null`. |
| `stackTrace` | The stack trace of the error, or `null`. |
| `requireValue` | The value, or an exception if there is none. |
These flags are not mutually exclusive, which surprises many people. Look at this example:
import 'package:riverpod/riverpod.dart';
void inspect(String label, AsyncValue<int> state) {
print(
'$label: isLoading=${state.isLoading} '
'hasValue=${state.hasValue} hasError=${state.hasError}',
);
}
void main() {
inspect('data', const AsyncData(42));
inspect('loading', const AsyncLoading());
inspect('error', AsyncError(Exception('boom'), StackTrace.current));
inspect(
'reloading',
const AsyncLoading<int>().copyWithPrevious(const AsyncData(7)),
);
}The output is:
data: isLoading=false hasValue=true hasError=false
loading: isLoading=true hasValue=false hasError=false
error: isLoading=false hasValue=false hasError=true
reloading: isLoading=true hasValue=true hasError=falseThe last line is the important one. A value in the AsyncLoading case can still carry the last data or error, so isLoading and hasValue can both be true. This is how Riverpod lets a screen keep showing the old list while a refresh runs in the background. The next chapters build on it, and a later chapter covers isRefreshing and isReloading in detail. For now, remember one rule: the subclass says what is happening now, and the flags tell you what else is available.
Why this is better than a Future
The same asynchronous operation, written two ways, shows the difference in practice. With a bare Future:
Future<List<String>> loadNames() async {
// May throw. Callers must remember to catch.
return ['Ada', 'Grace'];
}With AsyncValue the outcome becomes a value instead of control flow. The AsyncValue.guard helper runs a function and converts its result or exception into AsyncData or AsyncError:
import 'package:riverpod/riverpod.dart';
Future<AsyncValue<List<String>>> loadNames({required bool fail}) {
return AsyncValue.guard(() async {
if (fail) throw StateError('server unavailable');
return ['Ada', 'Grace'];
});
}
Future<void> main() async {
print(await loadNames(fail: false));
print(await loadNames(fail: true));
}guard never throws. It catches anything thrown inside the callback and returns it as an AsyncError. The caller always receives a value it can store, pass around and render. Chapter 7 uses guard inside notifier methods. The point here is that failure has become data.
The comparison, summarized:
| Question | `Future<T>` | `AsyncValue<T>` |
|---|---|---|
| Can I read the current state synchronously? | No. | Yes. |
| Does it represent "loading"? | Only as "not yet completed". | Yes, as `AsyncLoading`. |
| Can it return to loading after a result? | No. | Yes. |
| Can it keep old data while loading again? | No. | Yes, through the previous value. |
| Is the error case part of the type? | No. | Yes, as `AsyncError`. |
| Does the compiler check that I handle every case? | No. | Yes, with a `switch`. |
Common mistakes
- Treating
isLoadingas "no data yet". During a reload,isLoadingis true andhasValueis also true. If you show a spinner wheneverisLoadingis true, you hide data that is still valid. Decide what the screen should show for each combination, or use thewhenand pattern-matching tools from the next chapter. - Calling
requireValueinbuild. At start-up the state isAsyncLoadingwith no value, so this throws on the first frame. - Swallowing errors by reading only the value. If you check
hasValueand never look athasError, a failed load renders as an empty screen with no explanation. - Passing a null stack trace. The
AsyncErrorconstructor needs aStackTrace. Use the one from yourcatch (error, stackTrace)clause, orStackTrace.current. - Confusing
AsyncValue<T>with aFuture<T>you can await. AnAsyncValueis a snapshot. You cannotawaitit. To wait for the result of anAsyncNotifier, you read the provider's.future, which a later chapter covers.
Where AsyncValue fits in the plan
The rest of the tutorial builds on this one type:
- The next chapter renders
AsyncValuein widgets withwhenand pattern matching. AsyncNotifierexposes anAsyncValueas itsstate.- The
build()method returns aFuture, and Riverpod wraps the result intoAsyncLoading,AsyncDataorAsyncErrorfor you. AsyncValue.guardturns a mutation's outcome into the same value.- Refresh and reload behavior is expressed through the previous-value mechanism you saw above.
If you remember only one thing, remember this: in Riverpod the answer to "what is the state of this async operation?" is always an AsyncValue, and an AsyncValue is always exactly one of three subclasses, possibly carrying earlier data.
Exercise
A provider is reloading and its state is const AsyncLoading<int>().copyWithPrevious(const AsyncData(7)). What are the values of isLoading and hasValue, and why is it useful that both can be true?
Show answer
Both are true. The state is an AsyncLoading case, so isLoading is true, but it still carries the previous value 7, so hasValue is true. A widget can keep showing 7 while the reload runs, and optionally show a small progress indicator, instead of replacing the screen with a spinner.
Exercise
Write a function AsyncValue<String> parse(String text) that returns AsyncData with the integer parsed from text, formatted as a string such as 'n=12', or an AsyncError if parsing fails. Use AsyncValue.guard so no exception escapes. It should be asynchronous, so what does its return type need to be?
Show answer
The return type must be Future<AsyncValue<String>>, because guard takes an async callback and returns a future. For example: Future<AsyncValue<String>> parse(String text) => AsyncValue.guard(() async => 'n=${int.parse(text)}');. Calling parse('12') completes with AsyncData('n=12'). Calling parse('x') completes with an AsyncError that holds the FormatException.