Sub topic 5
Loading initial data in build()
This chapter covers the build() method of an AsyncNotifier: when Riverpod calls it, what its return value becomes, and which mistakes cause trouble. It assumes you can read Dart Future, async and await, and that you know ref.watch and ref.read. You should also know the AsyncValue states (AsyncLoading, AsyncData, AsyncError) from the earlier chapters.
What build() is for
An AsyncNotifier<T> is a class that owns an AsyncValue<T>. Riverpod needs a first value for that state, and build() supplies it. The method has two jobs:
- It returns the initial value, or a
Futurethat completes with it. - It declares the provider's dependencies, by calling
ref.watchon other providers.
Here is the notifier from the running todo example, reduced to the load:
import 'package:flutter_riverpod/flutter_riverpod.dart';
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);
}
final todoRepositoryProvider = Provider<TodoRepository>((ref) {
throw UnimplementedError('Override with a real repository');
});
class TodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() {
return ref.watch(todoRepositoryProvider).fetchTodos();
}
}
final todosProvider =
AsyncNotifierProvider<TodosNotifier, List<Todo>>(TodosNotifier.new);The method has no try, no catch and no assignment to state. You return a Future<List<Todo>>, and Riverpod turns it into an AsyncValue<List<Todo>> for you.
What Riverpod does around your build()
The first time anything reads todosProvider, Riverpod creates a TodosNotifier and calls build(). Three things follow:
stateis set toAsyncLoadingbefore your future completes.- When the future completes with a value,
statebecomesAsyncDataholding that value. - When the future completes with an error, or
build()throws,statebecomesAsyncErrorholding the error and stack trace.
Your widget never calls build(). It only watches the provider and receives each new AsyncValue.
When build() runs again
build() is not called on every read. It runs:
- once, when the provider is first read;
- again after
ref.invalidateorref.refreshon the provider; - again when something you passed to
ref.watchinsidebuild()changes; - again if an
autoDisposeprovider lost all listeners and was destroyed, and is then read afresh.
Without autoDispose, the notifier and its state stay alive for the lifetime of the ProviderContainer. Two widgets that watch todosProvider share one load, not two.
Later chapters cover how the later runs behave, including keeping the previous data on screen. Here the point is that build() is the single place that describes how to get the data, so each of these triggers repeats the same load.
The return type is FutureOr<T>
The declared return type of AsyncNotifier<T>.build is FutureOr<T>. That means you can return a T directly or a Future<T>. Both of these are valid:
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class GreetingNotifier extends AsyncNotifier<String> {
@override
FutureOr<String> build() {
return 'Hello';
}
}
final greetingProvider =
AsyncNotifierProvider<GreetingNotifier, String>(GreetingNotifier.new);Because the value is returned synchronously, the first state is AsyncData and no AsyncLoading frame appears. This is useful when a notifier sometimes has the data already, for example from an in-memory cache, and otherwise falls back to the network. In that case declare FutureOr<T> and return the cached value in one branch and a future in the other.
Write Future<T> build() async { ... } when you always await something. Write FutureOr<T> build() only when a synchronous path really exists.
Errors in build()
If build() throws, or the future it returns fails, the provider is in AsyncError. Riverpod catches the failure for you, so a try/catch that only logs and rethrows adds nothing. Catch an exception only when you can turn it into a meaningful value, such as an empty list for "not found".
You can see both outcomes in a test. It uses a notifier that fails on purpose and a counter that shows how often build() runs.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class CountingNotifier extends AsyncNotifier<int> {
static int builds = 0;
@override
Future<int> build() async {
builds++;
await Future<void>.delayed(const Duration(milliseconds: 10));
return builds;
}
}
final countingProvider =
AsyncNotifierProvider<CountingNotifier, int>(CountingNotifier.new);
class FailingNotifier extends AsyncNotifier<int> {
@override
Future<int> build() async {
throw StateError('backend is down');
}
}
final failingProvider =
AsyncNotifierProvider<FailingNotifier, int>(FailingNotifier.new);
void main() {
test('build runs once however often the provider is read', () async {
CountingNotifier.builds = 0;
final container = ProviderContainer();
addTearDown(container.dispose);
expect(container.read(countingProvider), isA<AsyncLoading<int>>());
await container.read(countingProvider.future);
await container.read(countingProvider.future);
expect(CountingNotifier.builds, 1);
expect(container.read(countingProvider).requireValue, 1);
});
test('an exception in build becomes AsyncError', () async {
final container = ProviderContainer();
addTearDown(container.dispose);
await expectLater(
container.read(failingProvider.future),
throwsA(isA<StateError>()),
);
final state = container.read(failingProvider);
expect(state, isA<AsyncError<int>>());
expect(state.error, isA<StateError>());
});
}The first read returns AsyncLoading because the Future has not completed yet. Reading .future twice does not start a second load, because it exposes the future of the build already in flight or finished. The second test shows that nothing in FailingNotifier converts the exception. The AsyncError comes from Riverpod.
Using ref inside build()
The notifier has a ref property, and inside build() it is the main way to reach other providers. The rule is the same as for any provider body:
| Call | Use in build() | Effect |
|---|---|---|
| `ref.watch(other)` | Yes, for anything the loaded data depends on | Re-runs `build()` when `other` changes |
| `ref.read(other)` | Rarely, for one-off values that must not trigger a reload | Reads once, no subscription |
| `ref.listen(other, ...)` | For side effects such as logging | Runs a callback, does not rebuild |
In the todo example, ref.watch(todoRepositoryProvider) means that if the repository provider is overridden or replaced, the todos load again from the new repository. Methods on the notifier, such as addTodo, do the opposite and use ref.read, because a method runs once and should not subscribe to anything.
A safe habit is to read all dependencies at the top of build(), before the first await:
class TodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() async {
final repository = ref.watch(todoRepositoryProvider);
final todos = await repository.fetchTodos();
return todos;
}
}Capturing repository first keeps the dependency list obvious, and it avoids using ref after the notifier may have been disposed while the await was pending.
Do not put mutation logic in build()
build() returns the initial value. It should not assign state. In an AsyncNotifier, whatever build() returns is the state, and a write to state from inside build() fights with that result.
Keep the two responsibilities apart:
build()loads data and declares dependencies.- Other methods change data and set
state. The next chapter covers them withAsyncValue.guard.
Do not start side effects in build() that you cannot repeat safely, such as sending an analytics event or posting to a server. build() may run again for any of the reasons listed above, and each run repeats the side effect.
Common mistakes
- Reading
state.valuetoo early. Right after the provider is created,stateisAsyncLoading, sostate.valueisnull.requireValuethrows when there is no value yet. Useawait futureinside a notifier method when you need the loaded data. For example,final current = await future;completes with the current list oncebuild()has finished. - Forgetting to return the future. Writing
build() async { repository.fetchTodos(); }returnsnull-like void and discards the result. The compiler usually catches this because the return type does not match. - Using
ref.readfor a dependency. If the repository can change and you wroteref.read(todoRepositoryProvider)inbuild(), the list will not reload when it does. - Using instance fields as state. A field such as
final _cache = <Todo>[]on the notifier belongs to one notifier instance. It can be lost or reset when the provider is disposed and recreated, so keep real state instate. - Expecting the widget to call build(). The widget gets an
AsyncValue, and Riverpod decides when to runbuild().
Consuming the result
The widget side stays the same however the data is loaded. It watches the provider and handles each case:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class TodoList extends ConsumerWidget {
const TodoList({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
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()),
);
}
}The first frame shows the spinner, because the first value is AsyncLoading. When build() completes, the same widget is rebuilt with AsyncData or AsyncError.
Choosing between sync and async build
| Situation | Declaration | First state |
|---|---|---|
| Always loads from network or disk | `Future<T> build() async` | `AsyncLoading`, then data or error |
| Sometimes has data in memory | `FutureOr<T> build()` | `AsyncData` immediately on the sync path |
| Data is always available instantly | Consider a plain `Notifier<T>` | No async state at all |
If no operation in build() can fail or take time, an AsyncNotifier only adds AsyncValue handling to every widget. Use a plain Notifier in that case.
Summary
build()returns the initial value, or aFutureof it, and Riverpod turns the outcome intoAsyncLoading,AsyncDataorAsyncError.- It runs on first read, after invalidate or refresh, and when a watched dependency changes. It does not run once per widget.
- Use
ref.watchfor dependencies the data relies on, and read them before the firstawait. - Throwing from
build()is the normal way to signal failure. Do not wrap it in try/catch unless you can recover. - Return a plain value with
FutureOr<T>only when a synchronous path exists.
Exercise
A notifier's build() contains final repo = ref.read(todoRepositoryProvider); return repo.fetchTodos();. A test then overrides todoRepositoryProvider with a second fake repository after the first load finished, but the list does not reload. Why, and what is the fix?
Show answer
ref.read reads the repository once and creates no dependency, so build() is not re-run when the provider's value changes. Change it to ref.watch(todoRepositoryProvider), which makes Riverpod re-run build() when the dependency changes.
Exercise
A widget calls ref.read(todosProvider).value!.length in a button handler right after the app starts, and it sometimes throws. What is happening, and how can code in a notifier method wait for the loaded list instead?
Show answer
Right after the provider is created, the state is still AsyncLoading, so value is null and the null check fails. Inside a notifier method, final current = await future; waits for build() to finish and returns the loaded list, or throws the build error if the load failed.