Sub topic 11
Keeping Rebuilds Small
This chapter assumes you can write a StatelessWidget and a StatefulWidget, and that you know setState schedules a new call to build. It also assumes you know what const means on a Dart constructor. The goal is to limit how much of the widget tree runs build when state changes.
What a rebuild costs
Rebuilding is cheap by design. A widget is a small immutable description, and creating one is little more than allocating an object. Flutter then compares the new description with the old one and updates the render objects only where something changed. For most screens you don't need to optimize.
Rebuilds become a problem in two cases:
- A
buildmethod does real work, such as sorting a large list, parsing data, or building hundreds of children. - State changes many times per second, for example during an animation, a drag, or a scroll listener.
In both cases the fix follows one rule: when state changes, rebuild as little of the tree as you can.
What happens when setState runs
Calling setState marks that widget's element as dirty. On the next frame, Flutter calls build on that element and on every descendant whose widget is not identical to the previous one.
The word "identical" matters. If a parent builds a child and the child is the exact same object as last time, Flutter skips it and its whole subtree. If the parent creates a new object, Flutter calls the child's build, even when the new object has the same field values.
Technique 1: Use const constructors
A const widget expression is created once at compile time. Every time a parent's build runs, it gets the same instance back. Because the instance is identical, Flutter does not rebuild that subtree.
Here is a page that holds a quantity. Without const, ProductDescription and Divider are recreated on every tap:
import 'package:flutter/material.dart';
class ProductDescription extends StatelessWidget {
const ProductDescription({super.key});
@override
Widget build(BuildContext context) {
debugPrint('ProductDescription build');
return const Text('A sturdy, well-made mug.');
}
}
class ProductPage extends StatefulWidget {
const ProductPage({super.key});
@override
State<ProductPage> createState() => _ProductPageState();
}
class _ProductPageState extends State<ProductPage> {
int _quantity = 1;
@override
Widget build(BuildContext context) {
return Column(
children: [
const ProductDescription(),
const Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
onPressed: () => setState(() => _quantity++),
icon: const Icon(Icons.add),
),
Text('$_quantity'),
],
),
],
);
}
}With const ProductDescription(), the debugPrint line runs once. Remove the const keyword and it prints on every tap. Dart also lets you omit const inside an already-const expression, but not inside a build that returns non-const widgets, so write it explicitly.
A widget can only have a const constructor when all its fields are final and every field value is a compile-time constant at the call site. If you pass DateTime.now() or a variable like _quantity, const is not allowed for that expression. The lint prefer_const_constructors in flutter_lints flags places where you can add it.
Technique 2: Push state down
const helps only for subtrees that never change. Often the part that changes is small, and the better fix is to move setState into a widget that wraps only that part.
Move the counter out of the page:
import 'package:flutter/material.dart';
class QuantityPicker extends StatefulWidget {
const QuantityPicker({super.key});
@override
State<QuantityPicker> createState() => _QuantityPickerState();
}
class _QuantityPickerState extends State<QuantityPicker> {
int _quantity = 1;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
onPressed: () => setState(() => _quantity++),
icon: const Icon(Icons.add),
),
Text('$_quantity'),
],
);
}
}
class ProductPage extends StatelessWidget {
const ProductPage({super.key});
@override
Widget build(BuildContext context) {
return const Column(
children: [
Text('A sturdy, well-made mug.'),
Divider(),
QuantityPicker(),
],
);
}
}ProductPage is now stateless and fully const. A tap rebuilds only QuantityPicker. The trade-off is that siblings can no longer read _quantity directly. If the description needs the quantity, the state has to live in a common ancestor again (see "Lifting state up"). Pick the lowest widget that is an ancestor of everything that needs the value.
Technique 3: Extract widgets, not helper methods
A common habit is to split a large build into methods:
Widget _buildHeader() => const Text('Header');This keeps the code tidy but does nothing for rebuilds. The method runs inside the parent's build, so it runs whenever the parent rebuilds, and there is no separate element for Flutter to skip. A separate StatelessWidget class has its own element, its own const constructor, and its own BuildContext. Prefer classes when the piece is reused or sits under a parent that rebuilds often.
Technique 4: Pass a prebuilt child
Some widgets rebuild their content on a frequent signal, such as an animation tick or a notifier change. These widgets accept a child parameter for the part that does not depend on the signal. ValueListenableBuilder is a good example:
import 'package:flutter/material.dart';
class CartBadge extends StatefulWidget {
const CartBadge({super.key});
@override
State<CartBadge> createState() => _CartBadgeState();
}
class _CartBadgeState extends State<CartBadge> {
final ValueNotifier<int> _items = ValueNotifier<int>(0);
@override
void dispose() {
_items.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Row(
children: [
ValueListenableBuilder<int>(
valueListenable: _items,
builder: (context, count, child) {
return Row(children: [child!, Text('$count')]);
},
child: const Icon(Icons.shopping_cart),
),
TextButton(
onPressed: () => _items.value++,
child: const Text('Add'),
),
],
);
}
}When _items.value changes, only the builder callback runs. The child (the icon) is built once and handed back each time, so it is identical across calls. AnimatedBuilder and AnimatedWidget follow the same pattern. Notice that this approach does not call setState at all. The notifier tells the builder to rebuild itself.
Technique 5: Keep build free of heavy work
Flutter may call build at any time, including every frame during an animation. Never put these in build:
- Sorting or filtering large collections
- Network calls or file reads
- Creating controllers, streams, or futures
Do the work in initState, in an event handler, or in a separate layer, and store the result in a field. A FutureBuilder that receives fetchData() directly in build starts a new request on each rebuild. Create the future once in initState and pass the stored field instead.
Measuring rebuilds
Find out where rebuilds happen before you change structure.
- Add
debugPrint('MyWidget build')to thebuildof the widget you suspect, and watch the console while you interact. - In Flutter DevTools, open the Performance view and the Widget Inspector. Enable the rebuild count tracking option to see how often each widget is rebuilt.
- Run in profile mode (
flutter run --profile) on a real device. Debug mode is slower and gives misleading frame times.
A widget that rebuilds often is not a problem by itself. Look for frames that exceed the frame budget (about 16 ms at 60 fps) and trace them back to the expensive build.
Choosing a technique
| Situation | Best first step |
|---|---|
| Static subtree under a widget that rebuilds | Add `const` |
| One small part of a large screen changes | Move `setState` into a small stateful widget |
| Frequent updates from a notifier or animation | `ValueListenableBuilder` or `AnimatedBuilder` with `child` |
| A long `build` split into `_buildX()` methods | Turn the pieces into widget classes |
| Slow `build` with computation | Move the work out of `build` |
Common mistakes
- Adding
consteverywhere by habit. It only helps when the widget would otherwise be recreated, and the analyzer usually tells you where it applies. - Splitting widgets so finely that state has to be passed through many layers. Readability and correct data flow come first.
- Calling
setStatein a scroll or pointer listener on a large widget. Move that state into a notifier or a small widget. - Assuming a rebuilt widget redraws its pixels. A rebuild only compares descriptions. If the render object's properties are unchanged, Flutter does not repaint it.
Exercise
A screen's _ScreenState calls setState every time a text field changes, and the same screen also shows a large const-less list of product cards that does not depend on the text. Describe two changes that reduce the rebuild work, and say how you would confirm the improvement.
Show answer
First, move the text field and its setState into its own small stateful widget (or use a TextEditingController with a ValueListenableBuilder), so typing no longer calls build on the screen that contains the list. Second, make the product card widgets use const constructors where their arguments are constants, or build the list in a separate widget class whose inputs do not change, so Flutter skips it when the parent rebuilds. To confirm, add debugPrint to the card's build or watch rebuild counts in DevTools while typing. The count should stay flat. Then check frame times in profile mode on a real device.