Sub topic 8
Keys: keeping State attached to the right widget
This chapter assumes you know the widget and element trees, Widget.canUpdate, and how a StatefulElement owns its State. It covers how keys change which element a widget is matched with, and therefore which State it gets.
The problem keys solve
An element is reused when the new widget at the same slot has the same runtime type and the same key. Without keys, "the same slot" means the same position among siblings. That is correct while the list only changes at the end. It goes wrong when children are reordered, inserted at the front, or removed from the middle.
Here is the rule from the Flutter source, paraphrased:
static bool canUpdate(Widget oldWidget, Widget newWidget) {
return oldWidget.runtimeType == newWidget.runtimeType &&
oldWidget.key == newWidget.key;
}State lives on the element, not on the widget. If an element is matched to a different widget, the State follows the element, so the data stays at the old position while the configuration moves.
Seeing the bug
The program below shows two tiles, each with its own tap counter. Tap A twice, then tap swap.
import 'package:flutter/widgets.dart';
void main() => runApp(
const Directionality(
textDirection: TextDirection.ltr,
child: SwapDemo(),
),
);
class Tile extends StatefulWidget {
const Tile({super.key, required this.label});
final String label;
@override
State<Tile> createState() => _TileState();
}
class _TileState extends State<Tile> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() => _taps++),
child: Text('${widget.label}: $_taps '),
);
}
}
class SwapDemo extends StatefulWidget {
const SwapDemo({super.key});
@override
State<SwapDemo> createState() => _SwapDemoState();
}
class _SwapDemoState extends State<SwapDemo> {
List<String> _labels = ['A', 'B'];
@override
Widget build(BuildContext context) {
return Column(
children: [
GestureDetector(
onTap: () => setState(() => _labels = _labels.reversed.toList()),
child: const Text('swap'),
),
Row(
children: [
for (final label in _labels)
Tile(key: ValueKey(label), label: label),
],
),
],
);
}
}With key: ValueKey(label), the counter A: 2 moves to the second position together with its label. Delete the key: argument and rerun. The row shows B: 2 A: 0. The first element was matched to the new first widget (B) because the types are equal and both keys are null. Its State kept _taps == 2 and only widget.label changed.
The diagram shows what the element does for each child slot.
How a multi-child update uses keys
RenderObjectElement.updateChildren is what Row, Column, and Stack use. It works in phases:
- It matches old and new children from the top while
canUpdateis true. - It matches from the bottom in the same way.
- For the remaining middle range, it builds a map from key to old element. Each new child with a key looks up its old element by key. Children without keys are not looked up and get a new element.
- Old elements that nobody claimed are deactivated.
Keys therefore only matter in the middle range, which is why the bug appears on reorders and mid-list inserts, not on appends.
Kinds of keys
| Key | Equal when | Scope | Typical use |
|---|---|---|---|
| `ValueKey<T>(v)` | same `T` and `v == v2` | siblings | list items with a stable id |
| `ObjectKey(o)` | `identical(o, o2)` | siblings | items identified by an object, no usable id |
| `UniqueKey()` | never equal to another instance | siblings | force a fresh element |
| `GlobalKey` | the same instance | whole app | move an element between parents, reach its `State` |
| `PageStorageKey` | like `ValueKey` | siblings | save scroll position and similar state |
Local keys (everything except GlobalKey) only need to be unique among children of the same parent. Two lists can use the same ids without conflict.
Using GlobalKey
A GlobalKey lets Flutter move an element, with its whole subtree and State, to a different place in the tree. The move must happen within one frame. It also gives you access to the element from outside:
import 'package:flutter/widgets.dart';
class CounterBox extends StatefulWidget {
const CounterBox({super.key});
@override
State<CounterBox> createState() => CounterBoxState();
}
class CounterBoxState extends State<CounterBox> {
int value = 0;
void increment() => setState(() => value++);
@override
Widget build(BuildContext context) => Text('$value');
}
final counterKey = GlobalKey<CounterBoxState>();
// Elsewhere: counterKey.currentState?.increment();Use GlobalKey sparingly. It is registered in a global table, and reaching into another widget's State couples your code to its internals. Prefer passing data and callbacks down.
Using a key to reset State on purpose
Changing the key makes canUpdate return false, so the old element and its State are discarded. This is a clean way to reset a stateful subtree when the data it represents changes:
import 'package:flutter/widgets.dart';
class UserForm extends StatefulWidget {
const UserForm({super.key, required this.userId});
final int userId;
@override
State<UserForm> createState() => _UserFormState();
}
class _UserFormState extends State<UserForm> {
@override
Widget build(BuildContext context) => Text('Editing user ${widget.userId}');
}
Widget buildForm(int userId) => UserForm(key: ValueKey(userId), userId: userId);When userId changes, a new _UserFormState is created, so initState runs again and old text-field input is gone. Without the key, the same State would stay and you would need to handle didUpdateWidget yourself.
Common errors
- Key on the wrong widget. The key must be on the widget that is the direct child of the list. If you wrap
Tilein aPaddingand put the key onTile, thePaddingis what the parent compares, and it has no key. - Index as key.
ValueKey(index)reproduces the position-based matching you were trying to avoid. Use a stable id from the data. UniqueKey()created inbuild. A new key on every build means no element ever matches, so allStateis lost on every rebuild. Create it once, inStateor in the data.- Duplicate keys among siblings. Flutter throws "Duplicate keys found" in debug builds. Duplicate
GlobalKeys in the tree throw a separate error. - Mismatched key types.
ValueKey<int>(1)andValueKey<String>('1')are not equal. The same applies toValueKey<int>(1)againstValueKey<num>(1), because the generic type is part of the runtime type.
Exercise
A Column has three unkeyed stateful Tile children showing items X, Y, Z, each with its own counter. The list changes to Y, Z, with X removed from the front. Which counters does the user see on Y and Z, and how would you fix it?
Show answer
Without keys, the elements are matched by position. The first element, which had X's counter, is updated with Y's widget, and the second with Z's. The third element is removed, so Z's old counter is dropped. The user sees Y with X's old count and Z with Y's old count. Give each Tile key: ValueKey(item.id) so elements are matched by identity and X's element is the one removed.
Exercise
Why does Tile(key: UniqueKey(), ...) written inside build make a tile lose its State on every rebuild of the parent?
Show answer
Each build creates a new UniqueKey, which is never equal to the previous one. Widget.canUpdate returns false, so the old element is unmounted and a new element with a fresh State is created.