Sub topic 1
How and why widgets rebuild
Large Flutter screens get slow when too much of the tree runs build on every change. Before you can shrink rebuilds, you need an accurate picture of what triggers one and what a rebuild costs. This chapter builds that model. Later chapters use it to measure and reduce rebuilds.
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Dart: classes, constructors,
finalfields, and closures. - Build screens with
StatelessWidgetandStatefulWidget. - Call
setStateand write abuildmethod. - Run a Flutter app on a device or emulator and read the debug console.
Three trees, one of them cheap
Flutter keeps three parallel trees.
- Widgets are immutable configuration objects. You create them in
build. They are small and cheap, and Flutter discards them freely. - Elements are the long-lived instances that sit in the tree. Each element holds a widget as its current configuration and, for stateful widgets, the
Stateobject. - Render objects do layout and painting. They are the expensive part, and Flutter reuses them whenever it can.
A rebuild means Flutter calls build on an element's widget and produces a new widget subtree. Flutter then compares that subtree with the existing elements. It updates elements in place when the new widget has the same runtimeType and the same key, and replaces them otherwise. If the configuration did not change, the render objects underneath stay as they were.
This is why a rebuild is not automatically a problem. Creating widgets is cheap. The cost comes from three things: running heavy code inside build, rebuilding thousands of widgets in one frame, and rebuilds that force new layout or paint work.
What triggers a rebuild
An element rebuilds only after something marks it dirty. In every case the framework calls markNeedsBuild on the element, which adds it to the list of dirty elements for the next frame.
| Trigger | What happens |
|---|---|
| `setState` on a `State` | The element for that `State` is marked dirty. |
| A parent rebuilds and passes a new widget instance | The framework updates the child element. For a non-`const` child, the child rebuilds. |
| An `InheritedWidget` changes | Every element that registered a dependency on it is marked dirty. |
| A `Listenable` notifies a builder | Widgets such as `ValueListenableBuilder`, `ListenableBuilder`, and `AnimatedBuilder` call `setState` internally. |
| A `State` receives a new widget | `didUpdateWidget` runs, then `build` runs. |
| Hot reload | The framework reassembles the tree and rebuilds everything. |
How a rebuild travels down the tree
setState rebuilds the widget that owns the State, and then, by default, everything below it. The framework processes dirty elements in order of depth, shallowest first. For each one it calls build and then walks the returned widget down through Element.updateChild.
At each child, updateChild makes one of three decisions:
- If the new widget is the identical instance as the old one, the framework does not update that child. It skips the whole subtree below it, unless a descendant was separately marked dirty.
- If the new widget has the same type and key but is a different instance, the framework updates the element with the new configuration. A stateless child then rebuilds. A stateful child runs
didUpdateWidgetand thenbuild, and keeps itsState. - If the type or key differs, the framework disposes the old element and creates a new one. A new element means a new
Stateand usually new render objects.
Decision 1 is the lever behind most rebuild optimizations. A const widget is canonicalized at compile time, so the same instance is returned on every build. Decision 3 explains why unstable keys are costly, which a later chapter covers.
A runnable example
This app logs every build call. Tap the button and watch the console.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: CounterDemo()));
class CounterDemo extends StatefulWidget {
const CounterDemo({super.key});
@override
State<CounterDemo> createState() => _CounterDemoState();
}
class _CounterDemoState extends State<CounterDemo> {
int _count = 0;
@override
Widget build(BuildContext context) {
debugPrint('CounterDemo build');
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Count: $_count'),
const BuildLogger(label: 'const child'),
BuildLogger(label: 'non-const child'),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}
class BuildLogger extends StatelessWidget {
const BuildLogger({super.key, required this.label});
final String label;
@override
Widget build(BuildContext context) {
debugPrint('$label build');
return Text(label);
}
}On the first frame, all three build methods print. After each tap, only these lines print:
CounterDemo build
non-const child buildThe const BuildLogger is the same instance every time, so the framework skips it. The non-const one is a new instance on every call, so it rebuilds even though its label never changes. The Dart analyzer's prefer_const_constructors lint flags this exact line. That is what the lint is for.
Rebuild is not the same as repaint
A frame has several phases: build, layout, paint, and compositing. A rebuild only runs the first phase. When the new widgets carry the same configuration as before, the existing render objects see no change. They are not marked for layout or paint, and the later phases skip them.
So a rebuild that produces equal widgets is mostly wasted build calls and widget allocation. A rebuild that changes size or appearance also triggers layout and paint. Keep both costs in mind when reading profiler output, because they need different fixes. A later chapter on repaint boundaries returns to this.
Why large screens suffer
On a small screen, a rebuild from the root is invisible. On a large screen, several problems add up:
- State lives too high. A
setStateat the top of a screen with hundreds of widgets rebuilds all of them for a change that affects one label. - Rebuilds are frequent. A scroll listener, text field, timer, or animation may fire every frame, which leaves about 16 ms per frame at 60 Hz and about 8 ms at 120 Hz.
builddoes real work. Sorting, filtering, parsing, or building large strings insidebuildrepeats on every rebuild.- Dependencies are broad. A widget that depends on a large inherited object rebuilds whenever any part of it changes.
The rest of this tutorial addresses these four causes in turn.
Common mistakes
- Calling
setStateduringbuild. Marking an element dirty while the framework is building raises an error. Move the change into an event handler,initState, orWidgetsBinding.instance.addPostFrameCallback. - Calling
setStateafterdispose. An async callback that finishes late throws in debug builds. Checkif (!mounted) return;before callingsetStateafter anawait. - Assuming a rebuild loses state. A stateful child with the same type and key keeps its
Statewhen its parent rebuilds. Only a changed type or key resets it. - Treating every rebuild as a bug. A rebuild of a handful of cheap widgets costs far less than the complexity of avoiding it. Optimize rebuilds that you have measured, not ones you merely suspect.
- Mutating state without
setState. Changing a field does not mark anything dirty, so the screen shows stale data until some other trigger fires.
A mental checklist
When a screen rebuilds more than you expect, ask these questions in order:
- Which element was marked dirty, and by which trigger?
- How high in the tree is that element?
- Which children does it recreate on each
build, and which could be reused as identical instances? - Does the rebuild change any layout or paint, or only repeat
buildcalls?
The next chapter shows how to answer the first two questions with tools instead of guesses.
Exercise
In the runnable example, you change const BuildLogger(label: 'const child') to BuildLogger(label: 'const child'), without the keyword. Tap the button once. Which build lines print, and why?
Show answer
Three lines print: CounterDemo build, const child build, and non-const child build. Without const, the widget is a new instance on every build call. The framework sees a different instance with the same type and key, so it updates the element and rebuilds the child. The Text('Count: $_count') line prints nothing because Text has no logging build.
Exercise
A screen has a StatefulWidget at its root that owns a bool _expanded flag. The flag affects only one small ExpansionPanel deep in the tree. Name the trigger, say which part of the tree rebuilds when you call setState, and say where the state should live instead.
Show answer
The trigger is setState, which marks the root's element dirty. The root's build runs again, and every non-const descendant is updated and rebuilt. The state should move down into a small stateful widget that wraps only the panel, so setState marks that small element dirty and leaves the rest of the screen alone.