Sub topic 1
Why Async State Needs More Than a Future
Prerequisites
This chapter assumes you know Dart Future, async, await, and try/catch. You should also know how Flutter widgets rebuild and how Riverpod uses Provider, ref.watch, and ref.read.
The examples use Riverpod's AsyncValue. Add flutter_riverpod to your Flutter project before running them.
The Problem with a Bare Future
A Future<T> represents one value that will be available later. For example:
Future<List<String>> loadTodos() async {
return ['Write tests', 'Review code'];
}This describes the eventual list, but a screen needs more information than the eventual result. While the request is running, the screen may need to show a progress indicator. If the request fails, it needs to show an error and perhaps a retry button. If a previous list is already visible, the screen may want to keep that list while loading newer data.
A bare Future does not describe these states as one value. You can handle them with separate fields:
List<String>? todos;
Object? error;
bool isLoading = false;This approach creates several problems:
todosanderrorcan both be set by mistake.isLoadingmay be forgotten or reset at the wrong time.- Every feature must repeat the same state-management code.
- The widget must understand how several fields relate to one another.
- Previous data, refreshes, and retries become harder to model consistently.
A Future is still useful for performing asynchronous work. It is simply too small to be the complete state model for an asynchronous screen.
AsyncValue: One Model for Three Outcomes
Riverpod provides AsyncValue<T>, which represents the current state of an asynchronous operation that produces a T.
The main states are:
| State | Meaning | Typical UI |
|---|---|---|
| `AsyncLoading` | The operation has not finished | Progress indicator |
| `AsyncData<T>` | The operation completed successfully | Content |
| `AsyncError` | The operation failed | Error message and retry |
These states are alternatives. A value is not simultaneously a successful result and a failed result. This makes invalid combinations harder to create.
For a list of todos, the type is:
AsyncValue<List<String>>The type says both what the operation produces and that the result may currently be loading or failed. A provider or widget can pass this one value through the application instead of coordinating separate fields.
import 'package:flutter_riverpod/flutter_riverpod.dart';
final todosProvider = FutureProvider<List<String>>((ref) async {
return ['Write tests', 'Review code'];
});
void inspectTodos(Ref ref) {
final state = ref.watch(todosProvider);
switch (state) {
case AsyncData(:final value):
print('Loaded ${value.length} todos');
case AsyncError(:final error):
print('Could not load todos: $error');
case AsyncLoading():
print('Loading todos');
}
}A FutureProvider automatically exposes its asynchronous result as an AsyncValue. Later, an AsyncNotifier will give you a place to load the initial value and change it in response to user actions.
Why the Model Matters to a Widget
A widget rebuilds when watched provider state changes. When the provider moves from loading to data, Riverpod gives the widget a new AsyncValue. The widget can then render the matching state.
This keeps responsibilities separate:
- The asynchronous provider performs or coordinates the work.
AsyncValuerecords the operation's current outcome.- The widget chooses how each outcome should look.
The model also leaves room for more detailed states. For example, Riverpod can keep previous data while a provider refreshes. The screen can show existing content and a smaller loading indicator instead of replacing the whole page with a blank spinner.
That distinction matters because initial loading and refreshing have different user experiences. Initial loading has no content to show. Refreshing may have useful content already available.
Choosing the Right Abstraction
Use a bare Future inside a function when the caller only needs to await one operation. For example, a repository method can return Future<List<Todo>>.
Use AsyncValue at the state boundary, where asynchronous work meets application or widget state. It gives consumers a stable shape for loading, success, and failure.
A repository can therefore stay focused on data access:
abstract class TodoRepository {
Future<List<String>> fetchTodos();
}A Riverpod provider can expose that work as observable asynchronous state. The UI does not need to know whether the data came from a network request, a database, or a test fake.
Exercise
Exercise
Why is a single AsyncValue<List<String>> safer than separate todos, error, and isLoading fields?
Show answer
AsyncValue represents loading, success, and failure as related alternatives, so consumers cannot accidentally interpret unrelated field combinations as valid state.