Sub topic 2
AsyncValue: loading, data and error as one value
This chapter assumes you know Dart Future, async, await, and try/catch. It also assumes basic Riverpod usage, including Provider, ref.watch, and ConsumerWidget.
A Future<T> represents work that will finish later. It does not by itself describe every state a screen needs. A screen usually needs to show:
- A loading indicator while the work is running.
- The result when the work succeeds.
- An error message when the work fails.
AsyncValue<T> is Riverpod's state model for this situation. It stores one of three main states: loading, data, or error.
Why a bare Future is not enough
Consider a request for a list of messages. A Future<List<Message>> eventually produces either a list or an error. However, the widget also needs to know whether the request is still running.
You could keep separate variables:
bool isLoading = true;
List<Message>? messages;
Object? error;This approach allows invalid combinations. For example, isLoading could be false while both messages and error are empty. Every widget would also need to understand how these variables relate.
AsyncValue<List<Message>> groups the related state into one value:
flowchart TD
A[Request starts] --> B[AsyncLoading]
B --> C[AsyncData with a list]
B --> D[AsyncError with error and stack trace]AsyncValue makes the possible states explicit. A widget can handle each state in one place instead of coordinating several independent fields.
The three main states
| State | Meaning | Typical UI |
|---|---|---|
| `AsyncLoading` | The operation has not produced a result yet | Progress indicator |
| `AsyncData<T>` | The operation succeeded with a value of type `T` | Content |
| `AsyncError` | The operation failed | Error message and retry action |
The type parameter describes the successful value. For example, AsyncValue<List<String>> means that the data state contains a List<String>.
An error state also contains a StackTrace. Keep it when logging or reporting failures because it identifies where the error occurred.
Reading AsyncValue with `when`
Riverpod providers commonly expose an AsyncValue. A widget can use when to provide one callback for each state:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final messagesProvider = FutureProvider<List<String>>((ref) async {
await Future<void>.delayed(const Duration(milliseconds: 300));
return ['Welcome', 'Your report is ready'];
});
class MessageList extends ConsumerWidget {
const MessageList({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final messages = ref.watch(messagesProvider);
return messages.when(
loading: () => const Center(
child: CircularProgressIndicator(),
),
error: (error, stackTrace) => Center(
child: Text('Could not load messages: $error'),
),
data: (items) => ListView(
children: [
for (final item in items) ListTile(title: Text(item)),
],
),
);
}
}ref.watch(messagesProvider) returns an AsyncValue<List<String>>. The when method forces the widget to account for loading, error, and data.
The data callback receives the actual List<String>, so it does not need to unwrap a nullable value. The error callback receives both the error object and its stack trace.
Reading states with Dart pattern matching
Dart 3 pattern matching provides another way to inspect an AsyncValue:
Widget messageCount(AsyncValue<List<String>> messages) {
return switch (messages) {
AsyncData(:final value) => Text('${value.length} messages'),
AsyncError(:final error) => Text('Error: $error'),
_ => const CircularProgressIndicator(),
};
}AsyncData(:final value) extracts the successful value. AsyncError(:final error) extracts the failure. The wildcard arm handles loading and any state not handled explicitly.
Use when when you want a clear, direct rendering structure. Use a switch expression when the result is a compact widget or when you want Dart's exhaustive pattern syntax.
AsyncValue is not the asynchronous operation itself. It is a snapshot of that operation's current state. Riverpod updates the snapshot as the operation moves from loading to data or error. Later, an AsyncNotifier will let you create and update these snapshots for more complex state.
Exercise
What should a widget render when a provider contains AsyncError<List<String>>, and why is the stack trace useful?
Show answer
It should render an error state, such as an error message and retry control. The stack trace helps locate the code path that caused the failure when diagnosing or reporting the error.