Sub topic 12
Under the hood: widgets, elements, and render objects
This chapter assumes you can write a StatelessWidget and a StatefulWidget, know what setState does, and have seen the State lifecycle (initState, didUpdateWidget, dispose). Here you will see what the framework does with the widgets you return from build. That explains why State survives rebuilds, why rebuilding is cheap, and why keys matter.
Three trees, not one
You write widgets, so it is natural to think of one tree. Flutter keeps three, each with a different job and lifetime.
| Tree | Class | Mutable? | Lifetime | Job |
|---|---|---|---|---|
| Widget tree | `Widget` | No, immutable | Short, often recreated every frame | Describes what the UI should look like |
| Element tree | `Element` | Yes | Long, reused across rebuilds | Holds the position in the tree and links the other two |
| Render tree | `RenderObject` | Yes | Long, tied to its element | Measures, lays out, paints, and handles hit testing |
The framework turns widgets into elements, and elements own render objects. Nothing flows the other way: a render object does not know which widget produced it.
Widgets are cheap blueprints
A widget is a small immutable object whose fields are configuration. Text('Hi') does not draw anything. It records the string and the style. Because creating one costs only a small allocation, build can return a completely new subtree on every call.
Widgets have two ways to produce output:
- Composing widgets, like
StatelessWidgetandStatefulWidget. Theirbuildreturns other widgets. They never paint anything themselves. - Configuring a render object, like
Padding,Text(throughRichText) andDecoratedBox. These subclassRenderObjectWidgetand implementcreateRenderObjectandupdateRenderObject.
So many widgets in your tree have no render object at all. A Greeting widget that returns a Text adds an element but no render object.
Elements are the real nodes
When the framework first meets a widget, it calls createElement() and mounts the result in the tree. The element stores a reference to its current widget, its parent, and its children. It stays in the tree until the widget at that position is removed or replaced by one that cannot be reused.
Two facts follow from this:
BuildContextis the element. Thecontextargument tobuildis theElementitself, seen through theBuildContextinterface. This is whyTheme.of(context)can walk up the tree: the element knows its parent.Statebelongs to the element. AStatefulWidgetcreates aStatefulElement, which callscreateState()once and keeps thatStateobject. Each rebuild gives the element a new widget instance, and the element hands it to the sameStateasState.widget.
That is the mechanism behind "the widget is immutable but state persists". The widget is replaced often. The element and its State are not.
Render objects do the work
A RenderObject handles layout, painting, and hit testing. It receives constraints from its parent, picks a size, positions its children, and paints. These objects are more expensive to create and update than widgets, so the framework avoids recreating them. When a widget changes, its element calls updateRenderObject on the existing render object. The render object compares the new values with the old ones and marks itself for layout or paint only if something differs.
The update rule: `canUpdate`
When a parent rebuilds, its element compares the old child widget with the new one. The rule is a single static method on Widget:
import 'package:flutter/material.dart';
void main() {
// Same runtimeType, no keys: the element is reused.
print(Widget.canUpdate(const Text('a'), const Text('b'))); // true
// Different runtimeType: the element is discarded.
print(Widget.canUpdate(const Text('a'), const Icon(Icons.add))); // false
// Same type, different keys: the element is discarded.
print(Widget.canUpdate(
const Text('a', key: ValueKey(1)),
const Text('a', key: ValueKey(2)),
)); // false
}canUpdate returns true when runtimeType and key both match. In the framework, Element.updateChild then decides what to do:
- If the new widget is
null, the old child element is removed. - If the old and new widgets are the same instance, nothing happens. This is what makes
constwidgets skip work. - If
canUpdateis true, the element keeps itself, receives the new widget, and rebuilds if needed. - Otherwise, the old element and its subtree are unmounted, including
disposeon anyState. A new element is created and mounted, includinginitState.
Case 4 is the source of most "my state disappeared" bugs.
Seeing it run
This app prints the identity of the widget, the State, and the BuildContext (the element) on every build of Probe. The parent creates a new Probe instance each time it rebuilds, because the constructor call is not const.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Host())));
class Host extends StatefulWidget {
const Host({super.key});
@override
State<Host> createState() => _HostState();
}
class _HostState extends State<Host> {
int _n = 0;
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => setState(() => _n++),
child: const Text('Rebuild parent'),
),
Probe(label: 'parent rebuilds: $_n'),
],
);
}
}
class Probe extends StatefulWidget {
const Probe({super.key, required this.label});
final String label;
@override
State<Probe> createState() => _ProbeState();
}
class _ProbeState extends State<Probe> {
int _taps = 0;
@override
Widget build(BuildContext context) {
debugPrint('widget=${identityHashCode(widget)} '
'state=${identityHashCode(this)} '
'element=${identityHashCode(context)}');
return ElevatedButton(
onPressed: () => setState(() => _taps++),
child: Text('${widget.label}, taps: $_taps'),
);
}
}Run it and tap each button:
- Tapping "Rebuild parent" prints a new
widgetnumber. Thestateandelementnumbers stay the same, and the tap count is kept. - Tapping the
Probebutton leaves all three numbers unchanged. Only that element is marked dirty, so the parent'sbuilddoes not run and the same widget instance is reused.
What `setState` does
setState runs your callback, then calls markNeedsBuild() on the element. The element adds itself to the framework's dirty list. On the next frame, the build phase processes dirty elements in order from the top of the tree, calls build on each, and runs updateChild for the results. Layout and paint follow, but only for render objects that were marked.
Two consequences:
- Several
setStatecalls in the same event produce one rebuild, because the element is already marked dirty. setStaterebuilds one subtree. Elements above it are not touched.
Edge cases and gotchas
Elements are matched by position, then by type and key. If a Column has two Checkbox children and you reorder them, the elements stay in place and only receive different widgets. A stateless child looks fine. A stateful child keeps its old State under the new widget, so the wrong item appears checked. Giving each child a ValueKey based on a stable id makes the framework match elements to widgets by key instead of by index.
Changing type resets state. Swapping Counter for Text and back disposes the State and creates a new one. The same happens if you wrap a widget in a new parent, for example adding a Padding around it conditionally. The child's element is now under a different parent type, so it cannot be reused. Keep the wrapper in place and change its properties, such as Padding(padding: EdgeInsets.zero), when you need the state to survive.
GlobalKey moves elements. A GlobalKey is unique across the whole tree. It lets the framework move an element, with its State, to another place within one frame. It also gives you access to the state from outside. It is more costly than a local key, so use it sparingly.
Context can outlive its element. After an await, the element may have been unmounted. Using the context then throws or does the wrong thing. Check if (!context.mounted) return; before using it, or if (!mounted) return; inside a State.
Not every widget owns an element you can inspect. const widgets that are identical share one instance. Several tree positions can then refer to the same widget object, each with its own element. This is safe because the widget holds no per-position data.
Why this design pays off
Separating the three trees lets Flutter do three things at once. You can write simple declarative code that rebuilds freely, because widgets are cheap. State is stable, because elements persist. Rendering is fast, because render objects change only when their values change. The cost is that you must understand canUpdate, because it decides when state lives or dies.
Exercise
A ListView shows rows built from [a, b, c], and each row is a StatefulWidget with a checkbox in its State. You tick the checkbox on row a, then the list is reordered to [c, b, a], and no keys are used. Which row looks ticked, and why? What is the fix?
Show answer
The first row looks ticked, which is now c. Without keys, canUpdate matches elements to widgets by position, type and key. All rows have the same type and key == null, so the first element, holding the ticked State, is reused for the first new widget, c. The fix is to give each row a stable key, for example ValueKey(item.id). The framework then matches elements by key, so the ticked State moves with a.
Exercise
In the Probe app, you change Host.build so that Probe is wrapped in if (_n.isEven) Padding(padding: EdgeInsets.all(8), child: Probe(...)) else Probe(...). What happens to the tap count when you tap "Rebuild parent"? Why?
Show answer
The tap count resets to 0 on every tap of the parent button. The child slot alternates between a Padding and a Probe. canUpdate is false for different runtime types, so the old element is unmounted, its State is disposed, and a new element with a new State is created.