Sub topic 5
How an element is mounted, updated, and unmounted
This chapter assumes you know the widget/element split from the previous chapters. It also assumes you have written a StatefulWidget with initState and dispose. It covers the stages an element goes through and how they map onto State callbacks.
The four lifecycle states
Every Element is in one of four states, tracked internally by the framework.
- Initial: the framework has created the element but not yet attached it to a parent.
- Active: the element is in the tree and takes part in builds.
- Inactive: the parent has dropped the element, but it is held for the rest of the frame in case something reclaims it.
- Defunct: the element has been unmounted and can never be used again.
Mounting
A parent mounts a new child through inflateWidget. That method calls widget.createElement(), then element.mount(parent, slot). Mounting does three things:
- It links the element to its parent and records its slot, which is its position among the parent's children.
- It moves the element from initial to active.
- It builds the subtree below it. For a
RenderObjectElement, it also creates the render object and attaches it to the render tree.
For a StatefulElement, the first build is where your State comes alive. The element calls createState() in its constructor. During the first build it runs initState, then didChangeDependencies, and only then the first build. This order is why you can't read an InheritedWidget with dependOnInheritedWidgetOfExactType inside initState. The element has not yet finished setting up its dependency tracking.
Updating
Most frames do not mount anything. They update. When a parent rebuilds, it hands each element a new widget through updateChild. That method chooses one of four outcomes:
| Situation | What the framework does |
|---|---|
| New widget is `null`, old child exists | Deactivates the old child |
| No old child, new widget exists | Inflates (creates and mounts) a new element |
| Old child exists and `child.widget == newWidget` (same instance) | Only updates the slot. No rebuild happens. |
| Old child exists and `Widget.canUpdate` is true | Calls `child.update(newWidget)` |
| Old child exists and `canUpdate` is false | Deactivates the old child, then inflates a new element |
The third row is why const widgets are cheap. An identical instance lets Flutter skip the whole subtree.
During update, the element stores the new widget and rebuilds. For a StatefulElement, it first calls State.didUpdateWidget(oldWidget), with widget already pointing at the new configuration. For a RenderObjectElement, it calls updateRenderObject, which pushes the new values onto the existing render object. The render object itself survives. It only decides whether to mark layout or paint dirty.
Deactivating and unmounting
Removing a child is a two-step process. First, deactivateChild detaches the element's render object from the render tree. It then moves the element to the BuildOwner's list of inactive elements, which calls deactivate on the element and on its State. The element is now inactive.
Second, at the end of the frame, BuildOwner.finalizeTree unmounts every element still in that inactive list. Unmounting calls State.dispose, marks the element defunct, and releases its references.
The delay exists for GlobalKey. If a widget with the same GlobalKey appears elsewhere in the tree during the same frame, inflateWidget finds the inactive element and reactivates it. The framework calls activate, reattaches the render object, and the State is preserved. The State sees deactivate, then activate, and never sees dispose.
Watching it happen
This example logs every State callback. Tapping cycles between three steps: no probe, a probe named A, and a probe named B.
import 'package:flutter/widgets.dart';
void main() => runApp(const Directionality(
textDirection: TextDirection.ltr,
child: Host(),
));
class Probe extends StatefulWidget {
const Probe({super.key, required this.name});
final String name;
@override
State<Probe> createState() => _ProbeState();
}
class _ProbeState extends State<Probe> {
@override
void initState() {
super.initState();
debugPrint('initState ${widget.name}');
}
@override
void didUpdateWidget(Probe oldWidget) {
super.didUpdateWidget(oldWidget);
debugPrint('didUpdateWidget ${oldWidget.name} -> ${widget.name}');
}
@override
void deactivate() {
debugPrint('deactivate ${widget.name}');
super.deactivate();
}
@override
void dispose() {
debugPrint('dispose ${widget.name}');
super.dispose();
}
@override
Widget build(BuildContext context) => Text(widget.name);
}
class Host extends StatefulWidget {
const Host({super.key});
@override
State<Host> createState() => _HostState();
}
class _HostState extends State<Host> {
int _step = 0;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() => _step = (_step + 1) % 3),
child: Column(
children: [
Text('step $_step'),
if (_step == 1) const Probe(name: 'A'),
if (_step == 2) const Probe(name: 'B'),
],
),
);
}
}The console output matches the table above:
- Step 0 to 1 prints
initState A. The element is mounted. - Step 1 to 2 prints
didUpdateWidget A -> B. The type and key match, so the element is reused and only the configuration changes. - Step 2 to 0 prints
deactivate B, thendispose Bat the end of the frame. The element is unmounted.
Mapping elements to State callbacks
| Element step | `State` callback |
|---|---|
| Mount, first build | `createState`, `initState`, `didChangeDependencies`, `build` |
| Update with a new widget | `didUpdateWidget`, `build` |
| An inherited dependency changes | `didChangeDependencies`, `build` |
| Deactivate | `deactivate` |
| Reactivate after a `GlobalKey` move | `activate` |
| Unmount | `dispose` |
Common mistakes
- Cleaning up in
deactivate.deactivatecan be followed byactivate, so tear down resources such as controllers and subscriptions indispose. - Calling
setStateafterdispose. This throws in debug builds. After anawait, checkif (!mounted) return;before usingsetStateorcontext. - Expecting
initStateon every change. If the type and key match, the element andStateare reused. Put code that reacts to new configuration indidUpdateWidget. - Assuming a rebuilt widget means a new
State. A newStateappears only when an element is inflated. That happens after a type change, a key change, or a position change in an unkeyed list.
Exercise
In the Probe example, you change step 1 so it shows Probe(key: ValueKey('A'), name: 'A') and step 2 shows Probe(key: ValueKey('B'), name: 'B'). Going from step 1 to step 2, which State callbacks run on the old probe, and why?
Show answer
canUpdate now returns false, because the keys differ (ValueKey('A') is not equal to ValueKey('B')). The framework does not call didUpdateWidget. It deactivates the old element, which calls deactivate A, and inflates a new element, which calls initState B. The old element is unmounted at the end of the frame, which calls dispose A.