Sub topic 7
Deriving state by composing providers
This chapter assumes you can already declare a Provider and a NotifierProvider. It also assumes you know the difference between ref.watch and ref.read in a ConsumerWidget. Here you will build providers that compute their value from other providers, and you will see why that is usually better than computing values inside widgets.
What a derived provider is
A derived provider is a provider whose create function calls ref.watch on one or more other providers. Riverpod records those calls as dependencies. When any dependency changes, Riverpod discards the derived value and runs the function again.
The smallest case turns the counter's int into a bool:
final isEvenProvider = Provider<bool>((ref) {
return ref.watch(counterProvider).isEven;
});A widget that watches isEvenProvider does not know the counter exists. It depends only on the bool. If the counter goes from 2 to 4, isEvenProvider recomputes to true again. Because the new value equals the old one, the widget does not rebuild.
The dependency graph
Riverpod builds a graph from your ref.watch calls. Each provider is a node, and each watch is an edge pointing to the provider that is watched. Computation is lazy. A provider runs only when something first reads it, and its result is cached until a dependency changes.
A worked example: a filtered task list
The example has three layers.
- Source state: the list of tasks and the current filter. Each is a
Notifier. - Derived state: the visible tasks and the count of open tasks.
- Widgets: they watch only the derived values they display.
Save this as lib/main.dart in a project that depends on flutter_riverpod. It runs as shown.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Task {
const Task({required this.id, required this.title, this.done = false});
final int id;
final String title;
final bool done;
Task toggled() => Task(id: id, title: title, done: !done);
}
enum TaskFilter { all, open, done }
class TasksNotifier extends Notifier<List<Task>> {
@override
List<Task> build() => const [];
void add(String title) {
state = [...state, Task(id: state.length + 1, title: title)];
}
void toggle(int id) {
state = [
for (final t in state)
if (t.id == id) t.toggled() else t,
];
}
}
class FilterNotifier extends Notifier<TaskFilter> {
@override
TaskFilter build() => TaskFilter.all;
void select(TaskFilter filter) => state = filter;
}
final tasksProvider =
NotifierProvider<TasksNotifier, List<Task>>(TasksNotifier.new);
final filterProvider =
NotifierProvider<FilterNotifier, TaskFilter>(FilterNotifier.new);
final visibleTasksProvider = Provider<List<Task>>((ref) {
final tasks = ref.watch(tasksProvider);
final filter = ref.watch(filterProvider);
return switch (filter) {
TaskFilter.all => tasks,
TaskFilter.open => tasks.where((t) => !t.done).toList(),
TaskFilter.done => tasks.where((t) => t.done).toList(),
};
});
final remainingCountProvider = Provider<int>((ref) {
return ref.watch(tasksProvider).where((t) => !t.done).length;
});
void main() => runApp(const ProviderScope(child: MyApp()));
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: TaskScreen());
}
}
class TaskScreen extends ConsumerWidget {
const TaskScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
appBar: AppBar(title: const RemainingLabel()),
body: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (final f in TaskFilter.values)
TextButton(
onPressed: () => ref.read(filterProvider.notifier).select(f),
child: Text(f.name),
),
],
),
const Expanded(child: TaskList()),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
final next = ref.read(tasksProvider).length + 1;
ref.read(tasksProvider.notifier).add('Task $next');
},
child: const Icon(Icons.add),
),
);
}
}
class RemainingLabel extends ConsumerWidget {
const RemainingLabel({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final remaining = ref.watch(remainingCountProvider);
return Text('$remaining open');
}
}
class TaskList extends ConsumerWidget {
const TaskList({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final tasks = ref.watch(visibleTasksProvider);
return ListView(
children: [
for (final t in tasks)
CheckboxListTile(
value: t.done,
title: Text(t.title),
onChanged: (_) => ref.read(tasksProvider.notifier).toggle(t.id),
),
],
);
}
}The filtering logic lives in one place. It is not repeated in widgets, and you can test it without Flutter. TaskList never learns that a filter exists. RemainingLabel never sees the task list.
When dependents rebuild
A Provider notifies its listeners only when the new value is not equal (!=) to the old one. This decides how much work a change causes.
| Change | `remainingCountProvider` | `visibleTasksProvider` |
|---|---|---|
| A task is added | Recomputes, may yield a new `int` | Recomputes, yields a new list |
| Filter changes from `all` to `open` | Not affected | Recomputes, yields a new list |
| A task is toggled | Recomputes, the count changes | Recomputes, yields a new list |
remainingCountProvider returns an int, so equal results are suppressed. A computed List is a different matter. Dart lists compare by identity, so each recomputation yields a new object and notifies listeners, even if the contents match. That is acceptable for one list. If a deeper chain depends on a list and rebuilds are costly, expose a value type with == defined, or end the chain with a scalar value.
Chaining and fan-out
Derived providers can depend on other derived providers. A pageCountProvider could watch visibleTasksProvider and divide its length by a page size. One source can also feed many derived providers, as tasksProvider does above. Each derived provider recomputes independently, and Riverpod computes each at most once per change, however many widgets watch it.
You can also derive from asynchronous providers. Watching a FutureProvider yields an AsyncValue, so the derived function must handle loading and error states. Alternatively, watch the .future of the provider and make the derived provider async:
final userProvider = FutureProvider<String>((ref) async => 'Ada');
final greetingProvider = FutureProvider<String>((ref) async {
final name = await ref.watch(userProvider.future);
return 'Hello, $name';
});greetingProvider is in a loading state until userProvider completes. It carries over an error from userProvider if one occurs.
Common errors
- Watching the notifier instead of the state.
ref.watch(tasksProvider.notifier)returns the notifier object. That object never changes, so the derived provider would never recompute. WatchtasksProviderfor the value. - Mutating state in place.
state.add(task)changes the existing list. The identity stays the same, so listeners are not told. Always assign a new list, asTasksNotifier.adddoes. - Circular dependencies. If A watches B and B watches A, Riverpod throws at runtime. Break the cycle by moving the shared logic into a third provider.
- Side effects in derived providers. The function can run many times. Do not write to other providers or show UI from it. Use
ref.listenin a widget for side effects. - Putting state in the derived provider. A
Providerhas no setter. If a value must be changed by the user, such as the filter, make it aNotifierand derive from it.
Exercise
Add a Provider<String> named summaryProvider to the example. It should return text such as 2 of 5 done. It should use only the existing providers. Which providers should it watch, and why should it not use ref.read?
Show answer
It should watch tasksProvider, and compute the total as tasks.length and the done count as tasks.where((t) => t.done).length. For example: final summaryProvider = Provider<String>((ref) { final tasks = ref.watch(tasksProvider); final done = tasks.where((t) => t.done).length; return '$done of ${tasks.length} done'; });. It must use ref.watch because ref.read would take a single snapshot. The summary would then stay at its first value when tasks were added or toggled. It does not need filterProvider, since the summary covers all tasks.