Sub topic 7
Rebuild Only What Changes with ValueListenableBuilder
Prerequisites and the working model
This chapter assumes you know basic Dart classes, StatelessWidget, StatefulWidget, setState, and the build method.
ValueListenableBuilder<T> is a Flutter widget that listens to a ValueListenable<T>. A ValueListenable exposes a current value and notifies listeners when that value changes. ValueNotifier<T> is the common implementation.
When the notifier changes, Flutter calls only the builder function owned by that ValueListenableBuilder. Its parent does not need to rebuild just because the value changed. This makes it useful for small, frequently changing parts of a large screen.
A focused example
The following app stores the like count in a ValueNotifier. Tapping the button changes the notifier, so the ValueListenableBuilder rebuilds the text that displays the count.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: LikePage(),
);
}
}
class LikePage extends StatelessWidget {
const LikePage({super.key});
@override
Widget build(BuildContext context) {
final likes = ValueNotifier<int>(0);
return Scaffold(
appBar: AppBar(title: const Text('Product')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('This content does not depend on likes.'),
ValueListenableBuilder<int>(
valueListenable: likes,
builder: (context, value, child) {
return Text('Likes: $value');
},
),
ElevatedButton(
onPressed: () => likes.value++,
child: const Text('Like'),
),
],
),
),
);
}
}The example demonstrates the rebuild boundary, but creating a notifier inside build is usually a mistake. The method can run many times, which would create many notifier objects and discard their values. Keep a long-lived notifier in a State object, a state-management class, or another owner whose lifetime matches the data.
For a notifier owned by a stateful widget, dispose of it when the widget leaves the tree:
class LikePanel extends StatefulWidget {
const LikePanel({super.key});
@override
State<LikePanel> createState() => _LikePanelState();
}
class _LikePanelState extends State<LikePanel> {
final ValueNotifier<int> likes = ValueNotifier<int>(0);
@override
void dispose() {
likes.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<int>(
valueListenable: likes,
builder: (context, value, child) {
return Text('Likes: $value');
},
);
}
}Cache static children
The child parameter is for a subtree that does not depend on the changing value. Flutter builds that subtree once and passes the same instance to the builder on later notifications.
ValueListenableBuilder<int>(
valueListenable: likes,
child: const Icon(Icons.favorite),
builder: (context, value, child) {
return Row(
children: [
Text('$value'),
child!,
],
);
},
)The icon does not read value, so it belongs in child. The text does read value, so it stays in the builder. This pattern reduces work without making the code difficult to follow.
Common errors and trade-offs
- A
ValueNotifiernotifies when itsvaluechanges. Mutating an object in place may not notify listeners.
```dart final items = ValueNotifier<List<String>>([]);
items.value.add('New item'); // The notifier does not know about this. items.value = [...items.value, 'New item']; // Notifies listeners. ```
- Do not use
ValueListenableBuilderfor unrelated state just to avoidsetState. A normal rebuild is often cheap, and extra notifiers can make ownership and disposal harder to understand. - Keep the builder small. Expensive calculations inside it still run whenever the value changes.
- Use a separate notifier when two pieces of UI change at different rates. One broad notifier can cause more rebuilding than several focused notifiers.
Exercise
Why should a static icon be passed through the child parameter instead of being created inside the builder?
Show answer
The child parameter lets Flutter reuse the same icon widget when the notifier changes, while the builder creates its returned subtree again for every notification.