Sub topic 2
Loading initial data in build()
This chapter assumes you know Dart async and await, basic Provider and ref.watch usage in Riverpod, and how a Flutter build method works.
How build() loads data
An AsyncNotifier holds state that arrives over time, such as a list fetched from a server. Its build method runs when the provider is first read. The Future that build returns sets the state to loading until the future completes, then stores the result as data or as an error. Riverpod wraps that state in an AsyncValue.
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);Rebuilding automatically when dependencies change
ref.watch inside build subscribes the notifier to another provider. When that provider's value changes, Riverpod calls build again and the list reloads. In the example, overriding todoRepositoryProvider with a different repository reloads the list from that repository. You do not trigger the reload yourself.
Changing state with AsyncValue.guard
Methods that change data set the state to AsyncLoading, then store the outcome. AsyncValue.guard runs a function and returns AsyncData on success or AsyncError on failure, so you do not need try/catch. Add this method to TodosNotifier:
Future<void> addTodo(String title) async {
final repository = ref.read(todoRepositoryProvider);
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
await repository.addTodo(title);
return repository.fetchTodos();
});
}Exercise
In the addTodo method, why is state set to AsyncLoading before AsyncValue.guard runs?
Show answer
It makes the UI show a loading indicator while the add and reload happen. Without it, the screen would keep showing the old data until the new state arrives.