Sub topic 5
Loading Initial Data in `build()`
Prerequisites and the loading model
This chapter assumes that you know Dart Future, async, await, and try/catch. You should also know Flutter's build method and basic Riverpod operations such as ref.watch and ref.read.
An AsyncNotifier uses its build() method to produce the provider's initial value. For an AsyncNotifier<List<Todo>>, the method returns a Future<List<Todo>>. Riverpod converts that future into an AsyncValue<List<Todo>> for you.
The provider therefore moves through a predictable sequence:
| Stage | Provider state | Meaning |
|---|---|---|
| Before the future completes | `AsyncLoading` | The initial request is running |
| Request succeeds | `AsyncData<List<Todo>>` | The list is available |
| Request fails | `AsyncError` | The list could not be loaded |
You do not need to assign these states manually in build(). Riverpod observes the returned future and creates the appropriate AsyncValue.
Declaring the repository dependency
Keep network, database, or file-system code in a repository. The notifier coordinates that code and exposes its result to the UI.
A repository provider gives the notifier a dependency that can be replaced in tests or configured differently for development and production:
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();
}
final todoRepositoryProvider = Provider<TodoRepository>((ref) {
throw UnimplementedError('Override with a real repository');
});
class TodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() async {
final repository = ref.watch(todoRepositoryProvider);
return repository.fetchTodos();
}
}
final todosProvider =
AsyncNotifierProvider<TodosNotifier, List<Todo>>(TodosNotifier.new);The generic type on AsyncNotifier<List<Todo>> says that successful state contains a list of todos. The provider has the same value type, so widgets receive an AsyncValue<List<Todo>>.
The build() method runs when Riverpod first needs todosProvider. The method watches todoRepositoryProvider, then returns the repository's future. Riverpod waits for that future and stores the result.
Why `ref.watch` belongs in `build()`
ref.watch both reads a provider and records a reactive dependency. In this example, TodosNotifier depends on todoRepositoryProvider. If that dependency changes, Riverpod can run build() again and obtain a new list.
Place the watch before starting the asynchronous work:
@override
Future<List<Todo>> build() async {
final repository = ref.watch(todoRepositoryProvider);
return repository.fetchTodos();
}This is different from ref.read. A read obtains the current value without subscribing to changes. Use read for one-time actions, such as a user-triggered mutation. Use watch in build() when a change in the dependency should cause the provider to rebuild.
Do not put a long-lived subscription or manually managed loading flag in this method. The returned future is the loading operation, and AsyncNotifier tracks it.
Handling failures
If fetchTodos() throws, Riverpod captures the exception and exposes it as AsyncError. A widget can render the error without the notifier wrapping build() in boilerplate try/catch.
The error still needs useful handling at the UI boundary. For example, a screen can show a retry button that calls ref.refresh(todosProvider) or ref.invalidate(todosProvider). Those reload operations are separate from the initial loading behavior covered here.
A repository should throw when it cannot fulfill the request. Avoid returning an empty list for every failure, because that makes “no todos” indistinguishable from “the data failed to load.”
Exercise
Why should build() use ref.watch(todoRepositoryProvider) instead of ref.read(todoRepositoryProvider) when the repository is a reactive dependency?
Show answer
ref.watch records the dependency, so Riverpod can rerun build() when that provider changes. ref.read only obtains the current value and does not create that automatic relationship.