Sub topic 6
Rebuilding Automatically When Dependencies Change
This chapter assumes you know Future, async, and await, and that you have used Provider, ref.watch, and ref.read in Riverpod. The key idea is that an AsyncNotifier can watch other providers from its build() method. When a watched provider changes, Riverpod runs build() again.
Dependencies are part of the provider
A dependency is another provider whose value is needed to calculate the current provider's value. For example, a project list depends on the currently selected project ID.
When you call ref.watch inside build(), Riverpod records that provider as a dependency. A later change to the dependency invalidates the current computation and starts a new one.
ref.read does not create this relationship. It reads a value once at the point where the code runs. Use it for one-time actions, such as responding to a button press. Use ref.watch when the provider should react to changes.
Watch a dependency in `build()`
The following example loads projects for the selected project group. Changing selectedGroupProvider causes ProjectListNotifier.build() to run again.
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Project {
const Project(this.name);
final String name;
}
abstract class ProjectRepository {
Future<List<Project>> fetchProjects(String groupId);
}
final projectRepositoryProvider = Provider<ProjectRepository>((ref) {
throw UnimplementedError('Override with a real repository');
});
final selectedGroupProvider = StateProvider<String>((ref) => 'work');
class ProjectListNotifier extends AsyncNotifier<List<Project>> {
@override
Future<List<Project>> build() {
final groupId = ref.watch(selectedGroupProvider);
final repository = ref.watch(projectRepositoryProvider);
return repository.fetchProjects(groupId);
}
}
final projectListProvider =
AsyncNotifierProvider<ProjectListNotifier, List<Project>>(
ProjectListNotifier.new,
);There are two dependencies here:
selectedGroupProviderdetermines which group to load.projectRepositoryProvidersupplies the object that performs the load.
If either provider changes, Riverpod recomputes projectListProvider. The returned Future becomes the new source of its AsyncValue.
Keep reactive reads in build(). A common mistake is to store a watched value in a field and expect that field to update automatically. Riverpod tracks provider reads while executing the provider, not arbitrary fields or local variables.
Change the dependency from a widget
A widget can update the selected group by writing to the StateProvider. It does not need to call a reload method on ProjectListNotifier.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class ProjectListScreen extends ConsumerWidget {
const ProjectListScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final selectedGroup = ref.watch(selectedGroupProvider);
final projects = ref.watch(projectListProvider);
return Column(
children: [
DropdownButton<String>(
value: selectedGroup,
items: const [
DropdownMenuItem(value: 'work', child: Text('Work')),
DropdownMenuItem(value: 'personal', child: Text('Personal')),
],
onChanged: (groupId) {
if (groupId != null) {
ref.read(selectedGroupProvider.notifier).state = groupId;
}
},
),
Expanded(
child: projects.when(
data: (items) => ListView(
children: [
for (final project in items)
ListTile(title: Text(project.name)),
],
),
loading: () => const Center(
child: CircularProgressIndicator(),
),
error: (error, stackTrace) => Center(
child: Text('Could not load projects: $error'),
),
),
),
],
);
}
}The widget watches both providers for different reasons. It watches selectedGroupProvider to display the current dropdown value. It watches projectListProvider to display the asynchronous result.
When the selection changes, the following sequence occurs:
- The state of
selectedGroupProviderchanges. - Riverpod notices that
projectListProviderwatches it. ProjectListNotifier.build()runs again with the new group ID.- The provider exposes loading, data, or error state for the new request.
- The widget rebuilds with the new
AsyncValue.
`watch` versus `read`
Use the following rule when choosing between the two methods:
| Method | Creates a reactive dependency? | Typical use |
|---|---|---|
| `ref.watch(provider)` | Yes | Values needed to calculate provider state |
| `ref.read(provider)` | No | One-time actions, commands, and event handlers |
For example, reading the selected group with ref.read inside build() would load the initial group, but later group changes would not trigger a rebuild of the project provider. That creates stale data.
Using ref.watch in an event handler is usually unnecessary. The handler is already running because of a user action, so ref.read is normally the appropriate choice there.
Exercise
Exercise
In ProjectListNotifier.build(), what happens if selectedGroupProvider is read with ref.read instead of watched with ref.watch?
Show answer
The provider reads the group only during that build. Later changes to selectedGroupProvider do not create a reactive dependency, so the project list does not automatically reload for the new group.