Sub topic 7
Rebuild only what changes with ValueListenableBuilder
Prerequisites
This chapter assumes you can write StatefulWidget classes and call setState. It also assumes you know that build runs again whenever a widget is marked dirty. Earlier chapters covered how rebuilds happen, how to measure them, and how to push setState down into small widgets. This chapter covers a second way to narrow rebuild scope: listening to a value from outside the widget tree.
The problem
Moving state into a small widget works well when the state and the UI that shows it can live together. Often they can't. A like count may be shown in an app bar badge and also in a detail panel, and a button elsewhere changes it. You could lift the state to a common parent and call setState there, but then the whole parent rebuilds on every change.
ValueListenableBuilder solves this. The state sits in an object that widgets can subscribe to. Only the widgets that subscribed, and only the part inside the builder function, rebuild when the value changes.
The three pieces
Three types work together.
| Type | Role |
|---|---|
| `ValueListenable<T>` | A read-only interface. It has a `value` getter and lets callers add and remove listeners. |
| `ValueNotifier<T>` | A `ChangeNotifier` that holds one value and implements `ValueListenable<T>`. Setting `value` notifies listeners. |
| `ValueListenableBuilder<T>` | A widget that subscribes to a `ValueListenable<T>` and calls its `builder` each time the value changes. |
The builder has this signature:
Widget Function(BuildContext context, T value, Widget? child)The child argument is the widget you passed to the child: parameter of ValueListenableBuilder. It is built once by the parent and handed back to your builder on every call.
Here is the example from the plan:
final ValueNotifier<int> likes = ValueNotifier<int>(0);
Widget buildLikeBadge() {
return ValueListenableBuilder<int>(
valueListenable: likes,
builder: (context, value, child) {
return Row(
children: [
Text('$value'),
child!,
],
);
},
child: const Icon(Icons.favorite),
);
}When likes.value changes, only the builder function runs again. It returns a new Row and a new Text, and it reuses the same Icon instance. Flutter sees an identical widget instance for the icon and skips rebuilding it.
A complete runnable example
The ValueNotifier below belongs to the State object. The screen's build runs once, and the button changes the value without calling setState.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: LikeScreen()));
class LikeScreen extends StatefulWidget {
const LikeScreen({super.key});
@override
State<LikeScreen> createState() => _LikeScreenState();
}
class _LikeScreenState extends State<LikeScreen> {
final ValueNotifier<int> _likes = ValueNotifier<int>(0);
@override
void dispose() {
_likes.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
debugPrint('LikeScreen build');
return Scaffold(
appBar: AppBar(title: const Text('Likes')),
body: Center(
child: ValueListenableBuilder<int>(
valueListenable: _likes,
builder: (context, value, child) {
debugPrint('badge builder: $value');
return Row(
mainAxisSize: MainAxisSize.min,
children: [Text('$value'), const SizedBox(width: 8), child!],
);
},
child: const Icon(Icons.favorite),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _likes.value++,
child: const Icon(Icons.add),
),
);
}
}Run it and tap the button several times. The console prints LikeScreen build once, then one badge builder line per tap. That output is the behavior you want: the large part of the screen stays still while one small part updates.
Ownership and disposal
A ValueNotifier is an object with listeners, so you must dispose of it. The rules are simple:
- Create the notifier in
initStateor as afinalfield of aStateclass, and calldispose()in theState.disposemethod. - Do not create a notifier inside
build. Each rebuild would make a new notifier, drop the old subscription, and lose the value. - A notifier that lives for the whole app, such as a top-level
final, needs no disposal. It is also global state, so tests and hot restarts can leave stale values behind. Prefer owning it in aStateor a provider unless you have a reason. ValueListenableBuilderremoves its own listener when it is disposed or when you pass it a different notifier. It never disposes the notifier itself, because it does not own it.
When does it notify?
The value setter in ValueNotifier compares the new value to the old one with ==. If they are equal, it does nothing and no listener runs. This has two consequences.
First, setting the same value is free. Writing _likes.value = 5 twice builds the badge once.
Second, changing an object in place does not notify. This code does nothing visible:
final ValueNotifier<List<String>> tags = ValueNotifier<List<String>>([]);
void addTagWrong(String tag) {
tags.value.add(tag); // Same list instance, no notification.
}
void addTag(String tag) {
tags.value = [...tags.value, tag]; // New list, notifies listeners.
}Treat values held by a ValueNotifier as immutable. For a custom class, either define == and hashCode (a record or a class with value equality works) or replace the instance on every change. If you need to mutate in place, extend ChangeNotifier and call notifyListeners() yourself. That gives up the equality check, so every call notifies.
The child parameter in practice
The child parameter matters when the builder output includes a subtree that does not depend on the value. Put that subtree in child: and place it inside the result with child!.
Two details are easy to miss:
childis nullable, sochild!crashes if you forget to passchild:. Only usechild!when you passed one. Otherwise writechild ?? const SizedBox.shrink()or ignore the argument.- A widget created inside the builder, even a
constone, is simply built again with the rest of the builder output.constalready lets Flutter skip it. Thechildparameter helps most when the cached subtree is notconst, for example because it takes a constructor argument that is only known at runtime.
Where to place the builder
The scope of a rebuild is the widget returned by the builder. Place the builder as low in the tree as possible.
// Too high: the whole card rebuilds when the count changes.
ValueListenableBuilder<int>(
valueListenable: likes,
builder: (context, value, _) => ProductCard(likeCount: value),
);
// Better: only the label depends on the count.
ProductCard(
likeLabel: ValueListenableBuilder<int>(
valueListenable: likes,
builder: (context, value, _) => Text('$value likes'),
),
);In the second version, ProductCard receives a widget as a parameter. That widget is the builder, which listens on its own. The card's own build does not run when the count changes.
Listening to more than one value
A ValueListenableBuilder takes exactly one listenable. For two or more values, you have three options.
- Nest builders. This is fine for two values, but the inner builder reruns whenever the outer one changes.
- Use
ListenableBuilderwithListenable.merge. It subscribes to every listenable in the list and calls the builder when any of them notifies.ListenableBuilderis available in Flutter 3.10 and later. - Combine the values into one notifier whose value is a record or small class, then read parts with a selector. The next chapter covers selectors.
final first = ValueNotifier<String>('Ada');
final last = ValueNotifier<String>('Lovelace');
Widget buildFullName() {
return ListenableBuilder(
listenable: Listenable.merge([first, last]),
builder: (context, child) => Text('${first.value} ${last.value}'),
);
}ListenableBuilder also works with any ChangeNotifier, so you can listen to a model class directly. It gives you no value argument, since a general Listenable has no value. You read the fields you need from the object.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The UI does not update after a list or object changes | The value was changed in place, so `==` saw no difference | Assign a new instance |
| The counter resets when the parent rebuilds | The notifier is created inside `build` | Create it in `initState` or a field of `State` |
| The whole screen still rebuilds on each change | The builder wraps a large subtree, or `setState` is also called | Move the builder down to the widget that shows the value |
| Null check error on `child!` | `child:` was not passed to the builder widget | Pass `child:` or handle null |
| "used after being disposed" error | The notifier was disposed while still referenced by a widget or a callback | Dispose it in the owning `State.dispose` only |
| Memory grows after leaving a screen | Manual `addListener` calls without `removeListener` | Prefer builders, which clean up for you |
When to leave it alone
A notifier adds a second place where state lives, and that has a cost in readability. Do not use it for a value that only one small StatefulWidget needs. Local setState in a small widget is simpler and has the same rebuild scope. Use ValueListenableBuilder when the value is shared between distant widgets, when the owner is a long-lived object such as a controller, or when the owning widget is large and you want to avoid calling setState on it. Confirm in DevTools that the rebuild you remove costs frame time before you add the extra structure.
Exercise
A screen's State class holds final ValueNotifier<List<int>> scores = ValueNotifier([]);. A button runs scores.value.add(10); and a ValueListenableBuilder<List<int>> below shows scores.value.length. The text never changes. Why, and how do you fix it? Also, where should scores.dispose() be called?
Show answer
add changes the existing list in place. The value setter is never called, so no notification is sent, and even if it were, the same list instance would compare equal to itself. Fix it by assigning a new list: scores.value = [...scores.value, 10];. Call scores.dispose() in the dispose method of the State that created the notifier, before super.dispose().
Exercise
You have a ValueListenableBuilder<int> whose builder returns Column(children: [Text('$value'), ExpensiveChart(data: chartData)]), where chartData is computed at runtime and does not depend on value. How do you stop ExpensiveChart from being rebuilt each time value changes?
Show answer
Create the chart once outside the builder and pass it as child: ExpensiveChart(data: chartData). In the builder, use child! (or a null-safe fallback) as the second item in the Column. The builder then returns a new Column and Text but reuses the same chart instance, so Flutter skips rebuilding it.