Sub topic 1
Why async state needs more than a Future
Almost every Flutter screen waits for something: a network call, a database read, a file. A Future represents one of those operations well. It does not represent what the screen needs to know while the operation runs, after it fails, or when you run it a second time. This chapter explains that gap. The rest of the tutorial fills it with AsyncValue and AsyncNotifier.
Prerequisites
This chapter assumes you already know:
- Dart async basics:
Future,asyncandawait, andtry/catch. - Flutter widgets and the
buildmethod, including thatbuildcan run many times. - Basic Riverpod usage:
Provider,ref.watchandref.read. - Dart 3 pattern matching. It is helpful for one later section and not needed here.
The examples use flutter_riverpod 2.x or later. They share the model and repository below, which later chapters reuse.
class Todo {
const Todo(this.id, this.title);
final String id;
final String title;
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
Future<void> addTodo(String title);
}What a Future tells you
A Future<T> is a promise of one result. It is in one of three situations: not finished, finished with a value, or finished with an error. You can await it, or attach callbacks with then and catchError.
A Future has no properties for asking "which of those three am I in right now?". The only way to find out is to await it, which gives you the value or throws. A widget cannot await in build, because build must return a widget synchronously. Something has to turn the Future's progress into a value that build can read on every frame.
Flutter's built-in answer is FutureBuilder. It listens to a Future and gives you an AsyncSnapshot with a connectionState, data and error. That works for a one-off display, but it has three problems, covered next.
Problem 1: who owns the Future
FutureBuilder takes a Future from you. If you create it inside build, every rebuild creates a new Future and starts the work again.
import 'package:flutter/material.dart';
class TodoPage extends StatelessWidget {
const TodoPage({super.key, required this.repository});
final TodoRepository repository;
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Todo>>(
// Bug: a new request starts on every rebuild of this widget.
future: repository.fetchTodos(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Failed: ${snapshot.error}'));
}
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
final todos = snapshot.data!;
return ListView(
children: [for (final todo in todos) ListTile(title: Text(todo.title))],
);
},
);
}
}A parent rebuild, a theme change, or a keyboard opening can all trigger it. The user sees the spinner flash again and the server gets duplicate requests. The usual fix is to move the Future into a StatefulWidget and create it in initState. That fixes one screen. It does not fix the following issues:
- Another screen that needs the same todos starts its own request.
- When the widget leaves the tree, the result is thrown away, so coming back loads everything again.
- To test the screen you must construct the widget with a fake repository by hand.
The Future needs an owner that lives outside the widget tree, is created once, and can be shared. Riverpod providers are that owner.
Problem 2: the snapshot can be in impossible states
Suppose you skip FutureBuilder and keep the state yourself in a notifier. A common first attempt uses separate fields:
class TodoState {
const TodoState({
this.todos = const [],
this.isLoading = false,
this.error,
});
final List<Todo> todos;
final bool isLoading;
final Object? error;
}This type allows combinations that should never exist. isLoading can be true while error is also set. todos is an empty list both before the first load and after a load that really returned nothing, so the UI cannot tell "not loaded yet" from "loaded, and empty". Every widget that reads this class must decide which field wins, and different widgets will decide differently.
Checks in build can drift apart as the code grows:
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(todoStateProvider);
if (state.isLoading) return const CircularProgressIndicator();
if (state.error != null) return Text('Failed: ${state.error}');
// What if the first load has not started yet? todos is empty, so the
// screen shows a blank list instead of a spinner.
return ListView(
children: [for (final todo in state.todos) ListTile(title: Text(todo.title))],
);
}The fix is to make the invalid combinations unrepresentable. A value should be exactly one of three cases, and each case should carry only the data that makes sense for it:
- loading: no data and no error
- data: a value
- error: an error object and a stack trace
In Dart 3 this is a sealed class hierarchy. Riverpod ships one, called AsyncValue<T>, with the subclasses AsyncLoading, AsyncData and AsyncError. The next chapter covers it in detail. For now, note the shape of the idea: your widget receives one value and handles each case explicitly.
Problem 3: the second load is not the first load
The first load of a screen is simple. There is nothing to show yet, so you show a spinner. The harder situation is the second one: the user pulls to refresh, or taps "retry", or adds an item and the list reloads.
If the state only has the three cases above, a reload has to go back to "loading". The list the user was reading vanishes and a spinner takes its place. That is a poor experience for a refresh that usually returns almost the same data.
The same applies to errors. A refresh fails while the screen already holds a good list. A plain error state throws the old list away. The user would probably prefer to keep seeing the old list and a small error message.
So a useful async state model needs more than three cases. Each case may also need to say whether it is a reload and what the previous value was. Riverpod's AsyncValue handles this by letting AsyncLoading and AsyncError carry the previous data when there is some. Later chapters cover the exact flags (isLoading, isRefreshing, isReloading) and how to use them.
Problem 4: changing state is also async
Reading is only half of it. Screens also write: create an item, delete one, toggle a flag. Each write has the same lifecycle as a read: it starts, it finishes, or it fails.
With a bare Future you write this by hand every time:
Future<void> addTodo(String title) async {
state = state.copyWith(isLoading: true, error: null);
try {
await repository.addTodo(title);
final todos = await repository.fetchTodos();
state = state.copyWith(todos: todos, isLoading: false);
} catch (e) {
state = state.copyWith(isLoading: false, error: e);
}
}This is correct but repetitive. Every mutation repeats the same set-loading, try, catch, set-error steps, and forgetting one branch (for example, not clearing isLoading in the catch) leaves the UI stuck on a spinner. The tutorial later replaces this block with AsyncValue.guard, which runs a function and returns either AsyncData or AsyncError for you.
The model Riverpod uses
Putting the four problems together gives these requirements:
| Requirement | Why a bare Future fails | What Riverpod provides |
|---|---|---|
| A single owner for the load | The widget creates the Future, so rebuilds restart it | A provider creates and caches the state |
| Exactly one state at a time | Separate flags allow impossible combinations | `AsyncValue` is a sealed type with three cases |
| Show old data during a reload | The state returns to "loading" and the data is lost | Loading and error cases can carry the previous value |
| Uniform handling of writes | Each mutation repeats try/catch boilerplate | `AsyncValue.guard` wraps the call |
| Testing without widgets | The Future lives inside the widget | A `ProviderContainer` runs providers in plain Dart tests |
The arrows from Data and Error back to Loading are the part a bare Future cannot express. A Future finishes once. An async state can run its load again and again.
A first look at the result
Here is the smallest possible Riverpod version of the screen from Problem 1. It uses FutureProvider, a simpler cousin of the AsyncNotifier you will build later. It shows how the pieces above fit.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final todoRepositoryProvider = Provider<TodoRepository>((ref) {
throw UnimplementedError('Override with a real repository');
});
final todosFutureProvider = FutureProvider<List<Todo>>((ref) {
return ref.watch(todoRepositoryProvider).fetchTodos();
});
class TodoPage extends ConsumerWidget {
const TodoPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosFutureProvider);
return todos.when(
data: (items) => ListView(
children: [for (final todo in items) ListTile(title: Text(todo.title))],
),
error: (error, stackTrace) => Center(child: Text('Failed: $error')),
loading: () => const Center(child: CircularProgressIndicator()),
);
}
}Compare it with the FutureBuilder version:
- The provider calls
fetchTodos()once. RebuildingTodoPagereads the cached state and does not make a new request. ref.watchreturns anAsyncValue<List<Todo>>, not a Future.whenforces you to supply all three cases, so you cannot forget the error branch.- The repository is reached through another provider. A test or a different build can replace it with an override.
Note that todosFutureProvider is read-only. It has no addTodo method and no place for mutation logic. When a screen needs to write as well as read, you need a class that owns both. That class is AsyncNotifier, which the tutorial reaches in the chapter on declaring one.
Common errors this model prevents
These mistakes are common when async state is handled with bare Futures:
- Creating the Future in
build. The request restarts on each rebuild. In Riverpod the provider creates it once. - Reading
snapshot.data!without checking. It throws a null error while loading.AsyncValuemakes you handle the loading case. - Ignoring errors. A Future that fails with nobody listening can surface as an unhandled exception. When a provider's state is
AsyncError,whenrequires anerrorcallback. - Treating an empty list as "not loaded". In a flag-based state,
[]means both things. InAsyncValue,AsyncData([])is a loaded, empty result andAsyncLoadingis not. - Clearing the screen on every refresh. Spinner replaces content because the state has no way to carry the old value. Riverpod's
AsyncLoadingcan carry it.
What comes next
The remaining chapters build the model piece by piece:
AsyncValueand its three cases.- Rendering it with
whenand with Dart 3switchpatterns. - Declaring an
AsyncNotifierand loading initial data inbuild(). - Reacting to dependency changes with
ref.watch. - Writing state with
AsyncValue.guard. - Keeping previous data visible during a reload.
- Reloading with
ref.invalidateandref.refresh. - Reading the provider's
.future, and testing withProviderContainer.
Exercise
A screen uses FutureBuilder with future: repository.fetchTodos() written directly inside build. A user opens the keyboard on the same screen and the list flashes a spinner and reloads. Explain why, and name the two properties a Riverpod provider has that prevent it.
Show answer
Opening the keyboard changes the layout and rebuilds the widget. Each build calls fetchTodos() again, which creates a new Future, so FutureBuilder sees a different Future, resets to the waiting state and shows the spinner while the request restarts. A provider prevents this because (1) it creates the load once and owns it outside the widget tree, and (2) it caches the resulting state, so a rebuilt widget reads the cached AsyncValue instead of starting another request.
Exercise
A hand-written state class has the fields List<Todo> todos, bool isLoading and Object? error. Give two states the type allows that should be impossible, and one state the UI cannot tell apart from another.
Show answer
Impossible states: isLoading is true while error is also non-null, and (depending on the code) isLoading is false, error is null and the first load has never run. Indistinguishable: "not loaded yet" and "loaded successfully with no todos" both look like an empty list with isLoading false and error null. A sealed type with loading, data and error cases removes all of these.
Exercise
Why can a plain three-case state (loading, data, error) still give a poor experience on pull-to-refresh, and what extra information does Riverpod's AsyncValue allow its loading and error cases to carry?
Show answer
On a reload the state has to move back to the loading case, so the list the user was reading is replaced by a spinner. If the reload fails, the error case likewise has no list to show. AsyncValue lets AsyncLoading and AsyncError carry the previous data when there is some, so the screen can keep showing the old list during a reload or after a failed one.