Sub topic 10
Limiting rebuilds with select
This chapter assumes you know ref.watch, ConsumerWidget, and Notifier from the earlier chapters. You should also know that Dart objects compare with ==, which defaults to identity unless a class overrides it.
The problem: watching a whole object
ref.watch(provider) rebuilds the widget whenever the provider publishes a new value that is not equal to the previous one. For a provider that holds a single int, that is exactly what you want. For a provider that holds an object with several fields, it can be too coarse.
Suppose a Profile has a name and an age. A widget that only shows the name still rebuilds every time the age changes, because the whole Profile is a new value. For one small Text this costs almost nothing. In a large subtree, or a widget doing expensive layout, the extra rebuilds add up.
select lets a widget subscribe to one piece of a provider's value. The widget rebuilds only when that piece changes.
How select works
You call select on the provider and pass a function that extracts the part you care about:
final name = ref.watch(profileProvider.select((p) => p.name));Internally, Riverpod does the following each time profileProvider publishes a new value:
- It runs your selector function on the new value.
- It compares the result with the result from the previous run, using
==. - It rebuilds the widget only if the two results are not equal.
The selector runs on every change of the source provider, so the widget itself is still notified. Riverpod just discards the notification when the selected value is unchanged.
A runnable example
The following app shows two labels and a button. Each label prints a message when it builds, so you can see which ones rebuild. Run it and watch the console while you tap the button.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Profile {
const Profile({required this.name, required this.age});
final String name;
final int age;
}
class ProfileNotifier extends Notifier<Profile> {
@override
Profile build() => const Profile(name: 'Ada', age: 36);
void birthday() => state = Profile(name: state.name, age: state.age + 1);
}
final profileProvider =
NotifierProvider<ProfileNotifier, Profile>(ProfileNotifier.new);
class NameLabel extends ConsumerWidget {
const NameLabel({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
debugPrint('NameLabel build');
final name = ref.watch(profileProvider.select((p) => p.name));
return Text('Name: $name');
}
}
class AgeLabel extends ConsumerWidget {
const AgeLabel({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
debugPrint('AgeLabel build');
final age = ref.watch(profileProvider.select((p) => p.age));
return Text('Age: $age');
}
}
class ProfilePage extends ConsumerWidget {
const ProfilePage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
body: const Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [NameLabel(), AgeLabel()],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(profileProvider.notifier).birthday(),
child: const Icon(Icons.cake),
),
);
}
}
void main() {
runApp(const ProviderScope(child: MaterialApp(home: ProfilePage())));
}On startup, both labels print once. After each tap, only AgeLabel build appears. NameLabel is skipped because 'Ada' == 'Ada'.
ProfilePage does not watch anything. It only calls ref.read inside the button callback, so it never rebuilds because of the profile.
Equality is the whole mechanism
Because select compares with ==, the type your selector returns decides whether it works.
| Selected value | Equality behavior | Result |
|---|---|---|
| `int`, `String`, `bool`, `double`, enums | Compared by value | Works as expected |
| A new `List` or `Map` built in the selector | Compared by identity, so never equal | Rebuilds on every change |
| A class without `==` overridden | Compared by identity | Rebuilds whenever a new instance is created |
| A class with `==` and `hashCode` overridden (or a record) | Compared by value | Works as expected |
Selecting a collection
This selector builds a new list on every run, so it never compares equal to the previous result:
// Rebuilds on every change of todosProvider, even when nothing relevant changed.
final done = ref.watch(
todosProvider.select((todos) => todos.where((t) => t.done).toList()),
);Select a primitive instead when that is all the widget needs:
final doneCount = ref.watch(
todosProvider.select((todos) => todos.where((t) => t.done).length),
);If the widget needs the filtered list itself, the list is a new object each time. Either accept the rebuild, or give your item type value equality and compare lists with a helper such as listEquals from package:flutter/foundation.dart inside your own provider logic.
Selecting several fields
To react to two fields, return a record. Records compare by value, so the selection is equal when both fields are equal:
final (name, age) = ref.watch(
profileProvider.select((p) => (p.name, p.age)),
);This requires Dart 3. If the widget needs most of the object's fields, selecting adds little, and a plain ref.watch is simpler.
Using select with async values
A provider that returns AsyncValue changes whenever it moves between loading, data, and error. A widget that only cares about one slice can select it. For example, to rebuild only when the number of todos changes:
final count = ref.watch(
todoListProvider.select((async) => async.value?.length ?? 0),
);The value getter returns the latest data, or null while there is none. In older Riverpod 2.x releases it is spelled valueOrNull. Check the version in your pubspec.yaml. Use this pattern only when you do not need to show loading or error states in that widget. If you do, use when on the full AsyncValue instead.
select with ref.listen and derived providers
select is not limited to ref.watch. Anything that accepts a provider as a source accepts a selected one. With ref.listen, the callback fires only when the selected value changes:
ref.listen<int>(
profileProvider.select((p) => p.age),
(previous, next) {
debugPrint('Age changed from $previous to $next');
},
);Inside another provider, select narrows what the derived provider depends on:
final greetingProvider = Provider<String>((ref) {
final name = ref.watch(profileProvider.select((p) => p.name));
return 'Hello, $name';
});Here greetingProvider recomputes only when the name changes. Without select, it would recompute on every birthday, although it would then produce an equal string and its own watchers would not rebuild.
When select is the wrong tool
- Split widgets first when the subtree is easy to separate. In the example above,
NameLabelandAgeLabeleach own their subscription. This often does more thanselecton a large widget. - Do not select to avoid cheap rebuilds. Flutter rebuilds are cheap for small widgets. Measure with the Flutter DevTools rebuild counts before adding selectors everywhere.
- Keep selectors pure and fast. The function runs on every source change. Do not put side effects or heavy computation in it.
- Do not select to hide stale data. If the widget must reflect the whole object, watch the whole object.
Summary
ref.watchrebuilds on any change to the provider's value.selectrebuilds only when the selected part changes.- The comparison uses
==, so the selected type must have value equality. - Records are a convenient way to select several fields.
selectalso works withref.listenand inside derived providers.- Prefer small widgets and measure before adding selectors broadly.
Exercise
A widget uses ref.watch(todosProvider.select((todos) => todos.where((t) => t.done).toList())) and still rebuilds every time any todo changes, including when the done list is identical. Why does this happen, and how would you change the selector if the widget only displays how many todos are done?
Show answer
The selector builds a new List on every run. Lists compare by identity, so the new list is never equal to the previous one, and Riverpod treats each result as a change. Because the widget only needs a count, select the count instead: ref.watch(todosProvider.select((todos) => todos.where((t) => t.done).length)). An int compares by value, so the widget rebuilds only when the number of done todos changes.
Exercise
Using the Profile example, write a selector that rebuilds a widget only when name or age changes, and explain why it works even though it returns two values.
Show answer
ref.watch(profileProvider.select((p) => (p.name, p.age))). The selector returns a Dart 3 record. Records compare by value, so two records are equal when both fields are equal, and the widget rebuilds only when the name or the age changes.