Sub topic 8
Select only the state a widget needs
This chapter assumes you can write StatelessWidget and StatefulWidget classes, you know what setState does, and you have seen ChangeNotifier or ValueNotifier before. It builds on the previous chapter, where ValueListenableBuilder rebuilt only the part of the tree that listens to one value.
The problem: one object, many readers
A real screen rarely keeps one integer in a notifier. It keeps a model with several fields, such as a user's name, avatar, unread count, and theme choice. If a widget listens to the whole model, it rebuilds on every notification, even when the field it displays did not change.
Here is a model like that, using ChangeNotifier:
import 'package:flutter/foundation.dart';
class UserModel extends ChangeNotifier {
String _name = 'Ada';
int _unread = 0;
String get name => _name;
int get unread => _unread;
void rename(String value) {
_name = value;
notifyListeners();
}
void receiveMessage() {
_unread++;
notifyListeners();
}
}A ChangeNotifier has no idea which field changed. notifyListeners() tells every listener to run. If a header widget shows only name and listens to the whole UserModel, each incoming message rebuilds the header for nothing.
A selector fixes this. A selector is a function that takes the whole state and returns the one slice a widget cares about. The framework compares the new slice with the old slice and rebuilds the widget only when they differ.
How a selector works
The mechanism is the same in every library:
- The widget subscribes to the source of state.
- When the source notifies, the selector runs on the new state.
- The result is compared with the previously stored result, using
==. - If the values are equal, nothing happens. If they differ, the widget is marked dirty and rebuilds.
Notice that the selector still runs on every notification. Selectors save you from rebuilding, not from being called. Keep them cheap: read a field, do not compute a large result.
Selecting with package:provider
With package:provider, context.select does this in one call. It subscribes the calling widget to the model, and it rebuilds the widget only when the selected value changes.
// With package:provider
class UserName extends StatelessWidget {
const UserName({super.key});
@override
Widget build(BuildContext context) {
final name = context.select<UserModel, String>((user) => user.name);
return Text(name);
}
}Compare it with the broad form:
final user = context.watch<UserModel>();
return Text(user.name);context.watch rebuilds on every notifyListeners(). context.select rebuilds only when user.name changes. When receiveMessage() runs, the UserName widget above does nothing.
Rules for context.select
- Call it inside
build. Do not call it ininitStateor in callbacks. Usecontext.readthere. - Select a value with a useful
==. Strings, numbers, booleans, enums, and records compare by value. Plain class instances compare by identity unless you override==. - Select the smallest value that answers your question. If you only need to know whether there are unread messages, select
user.unread > 0, notuser.unread. The widget then rebuilds when the answer flips, not on every count.
final hasUnread = context.select<UserModel, bool>((user) => user.unread > 0);Selecting without a package
You do not need a state-management package to get the same effect. Two plain-Flutter options exist.
One notifier per field
The simplest option is to split the model so each field has its own ValueNotifier. Then each widget listens to exactly one notifier with ValueListenableBuilder, as in the previous chapter.
import 'package:flutter/material.dart';
class UserState {
final ValueNotifier<String> name = ValueNotifier<String>('Ada');
final ValueNotifier<int> unread = ValueNotifier<int>(0);
}
final userState = UserState();
class NameLabel extends StatelessWidget {
const NameLabel({super.key});
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<String>(
valueListenable: userState.name,
builder: (context, value, _) => Text(value),
);
}
}A ValueNotifier only notifies when you assign a value that is not == to the old one. Setting name.value = 'Ada' when it already holds 'Ada' does nothing.
This approach works well for a handful of fields. It gets clumsy when many widgets need combinations of fields.
Derive a listenable from a model
When you want to keep one model but listen to one slice, you can build a small derived listenable. Listenable.merge combines several listenables into one, but that goes the wrong way: it widens the subscription. To narrow one, write a small adapter that listens to the model and republishes only when the slice changes.
import 'package:flutter/foundation.dart';
class SelectedListenable<T, R> extends ChangeNotifier
implements ValueListenable<R> {
SelectedListenable(this._source, this._selector)
: _value = _selector(_source) {
_source.addListener(_onSourceChanged);
}
final T _source;
final R Function(T) _selector;
R _value;
@override
R get value => _value;
void _onSourceChanged() {
final next = _selector(_source);
if (next != _value) {
_value = next;
notifyListeners();
}
}
@override
void dispose() {
(_source as Listenable).removeListener(_onSourceChanged);
super.dispose();
}
}Usage requires T to be a Listenable. Create the adapter once, for example in a State object, and dispose it with the widget:
final nameListenable = SelectedListenable<UserModel, String>(
userModel,
(user) => user.name,
);Then pass nameListenable to a ValueListenableBuilder. The builder rebuilds only when the name changes. This is the same idea that context.select implements for you.
Common errors
| Error | What happens | Fix |
|---|---|---|
| Selecting a new object each time, such as `(u) => [u.name, u.avatar]` | A new `List` is never `==` to the old one, so the widget rebuilds on every notification. | Select a record `(u.name, u.avatar)`, or select each field in a separate call. |
| Selecting the whole model, such as `(u) => u` | The same instance is returned every time, so the widget never rebuilds, even when fields change. | Select the field you display. |
| Mutating a selected list in place | The list instance stays the same, so `==` reports no change and the UI is stale. | Replace the list with a new one when it changes. |
| Using `context.select` in a callback | The package throws an error, because selection only works while building. | Use `context.read` in callbacks. |
| Expensive selector | The selector runs on every notification, so the cost is paid even when no rebuild follows. | Select a stored field or precompute it in the model. |
The first two rows are opposite failures. A selector that returns a fresh object rebuilds too often. A selector that returns a mutated instance rebuilds too rarely. In both cases the root cause is the same: the comparison uses ==, so the value you return must have meaningful equality.
// Records have value equality, so this rebuilds only when name or unread changes.
final summary = context.select<UserModel, (String, int)>(
(user) => (user.name, user.unread),
);Records require Dart 3 or later.
When a selector is not worth it
A selector adds a small amount of code and a mental cost. Skip it when:
- The widget is cheap and shallow, such as a single
Text. - The model has one field, so there is nothing to filter.
- The widget really does depend on most of the model.
Measure first, as in the earlier chapters. If the profile shows that a widget with a large subtree rebuilds on unrelated notifications, add a selector there. Otherwise, leave it alone.
Summary of the technique
- A selector narrows a subscription from "any change to the object" to "a change to this slice".
- The slice is compared with
==, so choose slices with value equality. context.selectdoes this inpackage:provider. Per-fieldValueNotifiers or a small adapter do it in plain Flutter.- Use selectors where measurement shows unrelated rebuilds on large subtrees.
Exercise
A widget calls context.select<CartModel, List<Item>>((cart) => cart.items.where((i) => i.selected).toList()). The widget rebuilds on every cart notification, even when no selection changed. Why, and how do you fix it?
Show answer
The where(...).toList() call creates a new List every time the selector runs. A new list is never == to the previous one, so the selector always reports a change. Fix it by selecting a value with value equality, for example the count with cart.items.where((i) => i.selected).length, or by storing the selected items in the model and replacing that list only when the selection changes.
Exercise
You select (user) => user.unread to show a red dot when the user has unread messages. The dot widget rebuilds each time a message arrives. How can you reduce rebuilds further?
Show answer
Select the boolean user.unread > 0 instead of the count. The result only changes between false and true, so the widget rebuilds when the dot appears or disappears, not on every new message.