Sub topic 3
The matching rule: runtimeType and key
This chapter assumes you can build screens with StatelessWidget and StatefulWidget, call setState, and lay out children with Column and ListView. It also assumes you know that Flutter rebuilds widgets often. Here you will see the test Flutter runs on every rebuild to decide whether an existing State object survives.
Widgets are descriptions, Elements are the live objects
A widget is an immutable description of part of the UI. Every build call creates new widget objects. Flutter also keeps a second tree of Element objects between frames. Each element is the live instance for one position in the UI. A StatefulElement holds a reference to its State object, and the State holds your fields such as _count.
When a parent rebuilds, Flutter does not recreate the elements. It walks the new widgets and the existing elements together and asks one question for each pair: can this element take on the new widget as its configuration? If yes, the element stays, keeps its State, and receives the new widget. If no, the element and its State are thrown away and a new element is created.
The test for that question is the matching rule.
The rule itself
The rule is a static method on Widget:
static bool canUpdate(Widget oldWidget, Widget newWidget) {
return oldWidget.runtimeType == newWidget.runtimeType &&
oldWidget.key == newWidget.key;
}Two widgets match when both conditions hold:
- They have the same
runtimeType. This is the exact class, not a superclass or a shared interface. - Their
keyvalues are equal under==. A key is an optional constructor argument, andnullis a valid value.
Nothing else is compared. Constructor arguments such as label play no part. A Counter(label: 'A') matches a Counter(label: 'B') as long as neither has a key, or both have equal keys.
What happens on each outcome
The method that applies the rule is Element.updateChild. Its logic, simplified, is:
- If the new widget is
null, deactivate the old child. - If the old child's widget is the identical object as the new widget, keep it. Only the slot is updated, and no rebuild of that subtree is needed. This is why
constwidgets are cheap. - If
Widget.canUpdatereturns true, callchild.update(newWidget). The element keeps itsState, and for a stateful element Flutter callsdidUpdateWidgetand then rebuilds. - Otherwise, deactivate the old element and inflate a new one from the new widget.
| Outcome | State object | Lifecycle calls on `State` |
|---|---|---|
| Match | Kept | `didUpdateWidget`, then `build` |
| No match | Old one discarded, new one created | Old: `dispose`. New: `initState`, `didChangeDependencies`, `build` |
A match does not mean "nothing changed". The new widget may carry different data. Your State reads it through the widget property, which now points to the newest configuration.
Seeing the rule run
This program lets you cycle through three configurations at the same position. Mode 0 and mode 1 are both a Counter with no key, so they match. Mode 2 wraps the counter in a Card, so the widget at that position has a different runtimeType.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Demo())));
class Counter extends StatefulWidget {
const Counter({super.key, required this.label});
final String label;
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
@override
void initState() {
super.initState();
debugPrint('initState for ${widget.label}');
}
@override
void didUpdateWidget(Counter oldWidget) {
super.didUpdateWidget(oldWidget);
debugPrint('didUpdateWidget ${oldWidget.label} -> ${widget.label}');
}
@override
void dispose() {
debugPrint('dispose for ${widget.label}');
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListTile(
title: Text('${widget.label}: $_count'),
onTap: () => setState(() => _count++),
);
}
}
class Demo extends StatefulWidget {
const Demo({super.key});
@override
State<Demo> createState() => _DemoState();
}
class _DemoState extends State<Demo> {
int _mode = 0;
Widget _current() {
switch (_mode) {
case 0:
return const Counter(label: 'One');
case 1:
return const Counter(label: 'Two');
default:
return const Card(child: Counter(label: 'Three'));
}
}
@override
Widget build(BuildContext context) {
return Column(
children: [
_current(),
TextButton(
onPressed: () => setState(() => _mode = (_mode + 1) % 3),
child: const Text('Next mode'),
),
],
);
}
}Run it, tap the tile a few times, then press the button.
- Mode 0 to mode 1: the label changes to "Two" but the count is kept. The console shows
didUpdateWidget One -> Two. The element matched, so the sameStatereceived a new widget. - Mode 1 to mode 2: the count resets to 0. The console shows
dispose for Twofollowed byinitState for Three. The widget at that position changed fromCountertoCard, so the rule failed. TheCounteris still in the tree, but it now sits one level lower, under a newCardelement, and gets a fresh element andState. - Mode 2 to mode 0: the same thing happens in reverse.
Matching is positional
The rule is applied to a pair, so the real question is which old element is paired with which new widget. For a single child, the answer is trivial: the one old child meets the one new child. For widgets with a list of children, such as Column, Row and Stack, Flutter compares by position by default. The first new child is checked against the first old child, the second against the second, and so on.
For multi-child widgets, RenderObjectElement.updateChildren does more than a plain index walk. It works in this order:
- Walk forward from the start of both lists, pairing children while
canUpdateis true. - Walk backward from the end of both lists, pairing children while
canUpdateis true. - For the remaining middle section, collect the old children that have a non-null key into a map. For each remaining new child, if it has a key and the map contains an old child with that key and a compatible type, reuse that element.
- Any old child left over is deactivated. Any new child without a match is inflated fresh.
Step 3 is the reason keys exist. Only old children with keys can be found out of order. An old child without a key in the middle section can never be matched to a new widget at a different index, even if the types are identical.
flowchart TDThe diagram below summarizes the decision for one pair.
Key equality
The second half of the rule uses == on keys, so it matters how keys define equality.
null == nullis true. Two widgets without keys always satisfy the key half of the rule. This is why unkeyed widgets of the same type are interchangeable by position.- A
ValueKey<String>('a')equals anotherValueKey<String>('a'). The comparison covers both the value and the generic type, soValueKey<int>(1)does not equalValueKey<num>(1)`. - A
UniqueKeyequals only itself. A newUniqueKey()on every build therefore never matches the previous frame's widget. - A key and
nullare not equal. Adding a key to a widget that previously had none fails the match for that slot, and theStateis replaced.
Keys are compared only among widgets competing for the same slot or the same sibling list. Two ValueKey('a') widgets under different parents do not conflict. Keys that must be unique across the whole app are GlobalKeys, covered in a later chapter.
Consequences you can predict
Once you know the rule, several behaviors that look odd become predictable.
- Same type, different data, no key: the
Stateis reused and the data changes under it. If yourStatecopiedwidget.labelinto a field ininitState, that field is now stale. Either read fromwidgetinbuild, or update the field indidUpdateWidget. - Wrapping or unwrapping: adding
Padding,Opacity,Visibilityor any other wrapper around a stateful widget changes the type at that position and resets its state. This also happens when a conditional returns different wrapper types for different branches. - Conditional children in a list: inserting
if (show) Banner()at the top of aColumnshifts every later child by one position. Dart's collectionifomits the element when false, so positions move. Unkeyed stateful siblings of the same type then pair with the wrong old elements. Flutter avoids this in some cases with the backward walk in step 2, but you should not depend on it. - Stateless widgets: the rule applies to them too, but nothing visible is lost on a mismatch because they hold no
State. The cost is only the rebuild of their subtree.
Common errors at this stage
- Putting state-resetting logic in
initStateand expecting it to run whenever the label changes. It runs only when the element is created. UsedidUpdateWidgetfor changes on a matching element. - Debugging a "state leaked to the wrong item" bug by looking at the data. The data is correct. The bug is that the
Stateobjects stayed at their positions while the widgets moved. - Using
runtimeTypechecks inside your own code to decide equality. The framework already does this, so rely on keys instead.
Exercise
A Column builds [Counter(label: 'X'), Counter(label: 'Y')]. The user taps X three times. Then the parent rebuilds with [Counter(label: 'Y'), Counter(label: 'X')] and no keys. What count does the first tile show and what label does it have? What changes if you give each Counter key: ValueKey(label)?
Show answer
Without keys, both widgets are Counter with a null key, so each new widget matches the old element at the same position. The first element keeps its State with count 3 and receives the widget labelled 'Y', so the first tile shows "Y: 3" and the second shows "X: 0". With ValueKey(label), the keys no longer match by position, so the framework finds the old elements by key in the middle-section map. The element holding count 3 moves to the second position with its widget 'X', so the tiles show "Y: 0" and "X: 3".