Sub topic 6
Rebuilding automatically when dependencies change
This chapter assumes you can write a basic AsyncNotifier with a build() method that loads data, and that you know ref.watch and ref.read from plain providers. By the end you will know how ref.watch inside build() keeps async state in sync with the providers it depends on. You will also know which states a widget sees while that happens, and which mistakes break it.
The idea: build() is a reactive function
In the previous chapter, build() loaded the initial data. That description is incomplete. build() is also the place where the notifier declares what it depends on. Every ref.watch call inside build() registers a dependency. When a watched provider changes, Riverpod discards the current state and runs build() again.
You never write a listener, a subscription or a manual refetch. The data is a function of its inputs, and Riverpod re-evaluates the function when an input changes.
import 'package:flutter_riverpod/flutter_riverpod.dart';
enum TodoFilter { all, open, done }
class Todo {
const Todo(this.id, this.title, {this.done = false});
final String id;
final String title;
final bool done;
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos({required TodoFilter filter});
}
class FakeTodoRepository implements TodoRepository {
static const _all = [
Todo('1', 'Write tests', done: true),
Todo('2', 'Review pull request'),
Todo('3', 'Ship it'),
];
@override
Future<List<Todo>> fetchTodos({required TodoFilter filter}) async {
await Future<void>.delayed(const Duration(milliseconds: 50));
return switch (filter) {
TodoFilter.all => List.of(_all),
TodoFilter.open => _all.where((t) => !t.done).toList(),
TodoFilter.done => _all.where((t) => t.done).toList(),
};
}
}
final todoRepositoryProvider =
Provider<TodoRepository>((ref) => FakeTodoRepository());
class TodoFilterNotifier extends Notifier<TodoFilter> {
@override
TodoFilter build() => TodoFilter.all;
void setFilter(TodoFilter filter) => state = filter;
}
final todoFilterProvider =
NotifierProvider<TodoFilterNotifier, TodoFilter>(TodoFilterNotifier.new);
class TodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() async {
final filter = ref.watch(todoFilterProvider);
final repository = ref.watch(todoRepositoryProvider);
return repository.fetchTodos(filter: filter);
}
}
final todosProvider =
AsyncNotifierProvider<TodosNotifier, List<Todo>>(TodosNotifier.new);TodosNotifier watches two providers: the selected filter and the repository. Changing either one triggers a new build().
Watching it happen
The following program listens to todosProvider and prints every state it passes through. Append it to the file above.
String describe(AsyncValue<List<Todo>> value) {
final kind = switch (value) {
AsyncData() => 'data',
AsyncError() => 'error',
_ => 'loading',
};
final items = value.hasValue ? '${value.requireValue.length}' : 'none';
return '$kind isLoading=${value.isLoading} items=$items';
}
Future<void> main() async {
final container = ProviderContainer();
final subscription = container.listen<AsyncValue<List<Todo>>>(
todosProvider,
(previous, next) => print(describe(next)),
fireImmediately: true,
);
await container.read(todosProvider.future);
container.read(todoFilterProvider.notifier).setFilter(TodoFilter.done);
await container.read(todosProvider.future);
subscription.close();
container.dispose();
}The output looks like this:
loading isLoading=true items=none
data isLoading=false items=3
loading isLoading=true items=3
data isLoading=false items=1The third line is the one to study. After the filter changed, the state went back to loading, but it still carries the three items from the previous build. Riverpod keeps the last value attached to the new AsyncLoading. The chapter on refreshing and reloading covers the exact flags. For now, remember that a rebuild caused by a dependency does not erase the data on screen unless your UI chooses to hide it.
The sequence of events
The widget only called setFilter. Everything after that happens inside the provider graph.
ref.watch, ref.read and ref.listen in build()
Three methods on ref look similar, but they have different effects inside build().
| Call | Registers a dependency | Re-runs `build()` on change | Typical use inside `build()` |
|---|---|---|---|
| `ref.watch(p)` | Yes | Yes | Inputs that determine the result, such as filters, user ids and repositories |
| `ref.read(p)` | No | No | Values you need once and that never change the result |
| `ref.listen(p, cb)` | Yes, as a listener | No, it calls the callback instead | Side effects such as logging or showing a message |
The most common mistake is using ref.read for an input that does matter. The code compiles and the first load works. After that, the list silently stops reacting to changes.
class BrokenTodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() async {
// Wrong: read does not subscribe. Changing the filter never reloads.
final filter = ref.read(todoFilterProvider);
return ref.watch(todoRepositoryProvider).fetchTodos(filter: filter);
}
}The reverse also goes wrong. Inside a method such as addTodo, use ref.read, not ref.watch. A method runs at one moment in time and has no business subscribing to anything. Riverpod asserts in debug mode when you call ref.watch outside build().
Watch before you await
build() can be async, and the code before the first await runs immediately. The usual advice is to gather every watched value first and only then do asynchronous work.
@override
Future<List<Todo>> build() async {
final filter = ref.watch(todoFilterProvider); // 1. read inputs
final repository = ref.watch(todoRepositoryProvider);
return repository.fetchTodos(filter: filter); // 2. then await
}This keeps the dependency list obvious to a reader. It also avoids a subtle problem: if a dependency changes while an earlier await is still pending, you might compare values captured at different times.
Stale results are ignored
Suppose the user taps "open" and then quickly taps "done". Two builds start, and the first request may finish after the second. Riverpod handles this for you. When a dependency changes, the pending build is considered out of date, and its result is dropped. Only the newest build can set the state.
This protects the state, but it does not cancel the network request. The old request still runs to the end. If the work is expensive, use ref.onDispose, which runs just before the next build(). It lets you cancel work or debounce.
final searchQueryProvider =
NotifierProvider<SearchQueryNotifier, String>(SearchQueryNotifier.new);
class SearchQueryNotifier extends Notifier<String> {
@override
String build() => '';
void setQuery(String query) => state = query;
}
class SearchResultsNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() async {
final query = ref.watch(searchQueryProvider);
final repository = ref.watch(todoRepositoryProvider);
var disposed = false;
ref.onDispose(() => disposed = true);
// Debounce: wait, then check whether a newer build replaced this one.
await Future<void>.delayed(const Duration(milliseconds: 300));
if (disposed) return const [];
final todos = await repository.fetchTodos(filter: TodoFilter.all);
return todos.where((t) => t.title.contains(query)).toList();
}
}
final searchResultsProvider =
AsyncNotifierProvider<SearchResultsNotifier, List<Todo>>(
SearchResultsNotifier.new,
);The value returned after disposed becomes true is never used, because a newer build owns the state by then. Returning an empty list is only a way to finish the method.
Limiting rebuilds with select
Watching a whole provider rebuilds build() on every change to it. If the notifier only needs one field of a larger object, use select. The provider then rebuilds only when that field changes, compared with ==.
class Settings {
const Settings({required this.showCompleted, required this.theme});
final bool showCompleted;
final String theme;
}
class SettingsNotifier extends Notifier<Settings> {
@override
Settings build() => const Settings(showCompleted: true, theme: 'light');
void setTheme(String theme) =>
state = Settings(showCompleted: state.showCompleted, theme: theme);
}
final settingsProvider =
NotifierProvider<SettingsNotifier, Settings>(SettingsNotifier.new);
class VisibleTodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() async {
// A theme change no longer reloads the todos.
final showCompleted =
ref.watch(settingsProvider.select((s) => s.showCompleted));
final todos = await ref
.watch(todoRepositoryProvider)
.fetchTodos(filter: TodoFilter.all);
return showCompleted ? todos : todos.where((t) => !t.done).toList();
}
}
final visibleTodosProvider =
AsyncNotifierProvider<VisibleTodosNotifier, List<Todo>>(
VisibleTodosNotifier.new,
);Without select, switching the theme would flash the loading state and refetch from the server for no reason.
What a rebuild does to your state
A dependency-triggered rebuild replaces the state completely. Anything a mutation method stored is gone once build() runs again. If addTodo had put an optimistic item into state, the next build() would overwrite it with whatever the repository returns. This is correct when the server is the source of truth. It is a problem if you keep local-only data in state.
Two practical consequences follow.
- Keep derived or local-only data in a separate provider instead of mixing it into the async state.
- Do not keep mutable data in fields of the notifier class. Treat the class as a holder for methods, and keep data in
state.
Rendering during a dependency-triggered reload
A widget watching todosProvider sees the AsyncLoading state with previous data after the filter changes. What it shows depends on how it consumes the value. The when method has flags that control this. With the defaults, a reload caused by a dependency change calls the loading branch, even though old data exists.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class FilteredTodoList extends ConsumerWidget {
const FilteredTodoList({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
return Column(
children: [
SegmentedButton<TodoFilter>(
segments: [
for (final filter in TodoFilter.values)
ButtonSegment(value: filter, label: Text(filter.name)),
],
selected: {ref.watch(todoFilterProvider)},
onSelectionChanged: (selection) => ref
.read(todoFilterProvider.notifier)
.setFilter(selection.first),
),
Expanded(
child: todos.when(
skipLoadingOnReload: true, // keep old rows while the new ones load
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 button handler uses ref.read, since it runs once in response to a tap. The build method uses ref.watch, since the screen must follow the state. With skipLoadingOnReload: true, the old list stays visible until the new one arrives. Without it, the spinner replaces the list on every filter change. Which one is better depends on the screen: a spinner is honest, while stale rows feel smoother but can mislead if the filter label has already changed.
Dependencies that are themselves async
A notifier can also depend on another async provider. Watching it directly gives you an AsyncValue, which you would have to unwrap by hand. The usual approach is to await its .future, which this tutorial covers in its own chapter. The rebuild rule is the same: when the upstream provider produces a new value, build() runs again.
Common errors
- The list never updates after a filter change. An input was read with
ref.readinstead ofref.watch. - The list reloads on unrelated changes. The notifier watches a large object. Narrow it with
select. - A debug assertion about
ref.watchfires.ref.watchwas called in a method such asaddTodo. Useref.readthere. - Local edits vanish. A rebuild replaced the state. Store the edits elsewhere or push them to the server before the next build.
- A spinner flashes over existing content. The widget uses the default
whenflags. SetskipLoadingOnReloadto true if you want the old data to stay.
Exercise
A TodosNotifier build() contains final userId = ref.read(currentUserIdProvider); followed by a fetch for that user. The user signs out and another user signs in, but the screen still shows the first user's todos. What is wrong, and what is the fix?
Show answer
ref.read does not register a dependency, so build() is not re-run when currentUserIdProvider changes. Replace it with ref.watch(currentUserIdProvider). The notifier then rebuilds, goes through a loading state, and fetches the new user's todos.
Exercise
You watch a Settings provider in build() but only use settings.pageSize. Changing the theme in the same object reloads the list. How do you stop that, and what does Riverpod compare to decide whether to rebuild?
Show answer
Use ref.watch(settingsProvider.select((s) => s.pageSize)). Riverpod compares the selected value with the previous one using ==, and rebuilds build() only when they differ.