Sub topic 7
Putting the key on the right widget
This chapter assumes you know the matching rule from earlier in the tutorial. Flutter reuses an Element, and the State it holds, only when the new widget has the same runtimeType and key as the old widget in that slot. You should also know how ValueKey fixes the reorder problem. Here the question is where in the subtree the key must go for that fix to work.
The rule: key the topmost widget of each item
Flutter compares widgets one parent at a time. When a parent Element updates, it lines up its old child Elements with its new child widgets and applies the matching rule to each pair. Keys only decide the pairing among siblings, meaning the direct children of one parent.
For a collection, the siblings are the items themselves. So the key must be on the widget that is the direct child of the list-like parent (Column, Row, ListView, Wrap, Stack and so on). That is the topmost widget of each item.
Suppose each item is Padding wrapping a CounterTile:
- Correct: put the key on the
Padding, becausePaddingis whatColumnholds. - Incorrect: put the key on the
CounterTileinside thePadding.
The second version looks reasonable, since the stateful widget carries the key. It still breaks, and the way it breaks is easy to misread.
What happens when the key is too deep
Take the three-item list from the earlier chapter and reverse it. This time each item is Padding(child: CounterTile(key: ValueKey(label))).
Columncompares its old and new children by type and key. All of them arePaddingwidgets with no key, so they match by position.- At position 0 the old
PaddingElement is reused. It now receivesPadding(child: CounterTile(key: ValueKey('C'))). - The
PaddingElement compares its old child (CounterTilewith keyA) to the new child (CounterTilewith keyC). The types are equal but the keys differ, so they do not match. - Flutter discards the old child Element, along with its State, and creates a new one. The new State starts at
_count = 0.
Here the counters are not left behind under the wrong label. They are reset. In a reversed A, B, C, tiles A and C lose their counts, and B keeps its count because it is in the middle and its key still matches. The result is arguably worse than the original bug, because a keyed widget now loses state that an unkeyed one would have kept at its position.
A runnable comparison
This program lets you switch between the two placements. It reuses the CounterTile from the earlier chapters, repeated here so the file runs as shown.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(home: Scaffold(body: SafeArea(child: PlacementDemo()))),
);
class CounterTile extends StatefulWidget {
const CounterTile({super.key, required this.label});
final String label;
@override
State<CounterTile> createState() => _CounterTileState();
}
class _CounterTileState extends State<CounterTile> {
int _count = 0;
@override
Widget build(BuildContext context) {
return ListTile(
title: Text('${widget.label}: $_count'),
onTap: () => setState(() => _count++),
);
}
}
class PlacementDemo extends StatefulWidget {
const PlacementDemo({super.key});
@override
State<PlacementDemo> createState() => _PlacementDemoState();
}
class _PlacementDemoState extends State<PlacementDemo> {
List<String> _labels = ['A', 'B', 'C'];
bool _keyOnOuter = true;
Widget _item(String label) {
const padding = EdgeInsets.symmetric(horizontal: 16);
if (_keyOnOuter) {
// Key on the widget that Column holds directly.
return Padding(
key: ValueKey(label),
padding: padding,
child: CounterTile(label: label),
);
}
// Key one level too deep: Column cannot see it.
return Padding(
padding: padding,
child: CounterTile(key: ValueKey(label), label: label),
);
}
@override
Widget build(BuildContext context) {
return Column(
children: [
for (final label in _labels) _item(label),
TextButton(
onPressed: () =>
setState(() => _labels = _labels.reversed.toList()),
child: const Text('Reverse'),
),
TextButton(
onPressed: () => setState(() => _keyOnOuter = !_keyOnOuter),
child: Text(_keyOnOuter ? 'Key is on Padding' : 'Key is on CounterTile'),
),
],
);
}
}To try it:
- Tap each tile a different number of times.
- Press Reverse. With the key on
Padding, each count follows its label. - Press the second button to move the key to
CounterTile. Switching placement changes the keys Flutter sees, so the counters reset. Tap the tiles again. - Press Reverse. Tiles A and C now reset to 0, and B keeps its count.
Items that are your own widgets
Often the item is a custom widget whose build method returns the Padding. In that case the topmost widget at the call site is your custom widget, and the key goes there:
Column(
children: [
for (final todo in todos) TodoRow(key: ValueKey(todo.id), todo: todo),
],
)You do not need to put keys on anything inside TodoRow's own build. Once Flutter matches the TodoRow Element correctly, its whole subtree comes along with it, including any State deeper down. One correct key at the item root protects every stateful descendant.
Wrappers that change what the parent holds
Some widgets change which widget is the direct child. Check what the parent actually holds, not what the item looks like on screen.
| Item structure | Direct child of the list parent | Put the key on |
|---|---|---|
| `CounterTile(...)` | `CounterTile` | `CounterTile` |
| `Padding(child: CounterTile(...))` | `Padding` | `Padding` |
| `Expanded(child: CounterTile(...))` in a `Row` | `Expanded` | `Expanded` |
| `Dismissible(child: ListTile(...))` | `Dismissible` | `Dismissible` (it requires a key) |
| `Card(child: Row(...))` returned from a helper method | `Card` | `Card` |
| `TodoRow(...)` that builds a `Padding` internally | `TodoRow` | `TodoRow` |
Expanded and Flexible are worth remembering. They are ParentDataWidgets, and a Row or Column sees them as the child. A key on the widget inside Expanded does not take part in the Row's matching.
Helper methods and builders
A helper method like _item(label) in the demo is just a function. It creates no Element of its own. Whatever it returns is what the parent sees, so the key goes on the returned widget, as the demo does.
ListView.builder follows the same rule. The widget your itemBuilder returns is the item root, and it needs the key:
ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
final todo = todos[index];
return TodoRow(key: ValueKey(todo.id), todo: todo);
},
)A builder list also has one extra detail. Flutter builds only the visible children, so it needs a way to find where an existing keyed child moved. The findChildIndexCallback parameter of ListView.builder gives it that. It receives a Key and returns the item's new index, or null if the item is gone. Without it, Flutter still gives correct results, but it can do extra work to match reordered children.
Keys only compare among siblings
A ValueKey, ObjectKey or UniqueKey is a LocalKey, and a LocalKey is compared only among the children of one parent. Two sibling lists in different parents can use the same values without clashing:
Column(
children: [
Column(children: [CounterTile(key: ValueKey('A'), label: 'A')]),
Column(children: [CounterTile(key: ValueKey('A'), label: 'A')]),
],
)This is legal because the two ValueKey('A') objects have different parents. The reverse is not legal. Two siblings under the same parent with equal keys cause a duplicate key error, which a later chapter covers.
The same scoping explains why you cannot move a keyed widget to a different parent with a LocalKey. The new parent has no old child with that key to match, so the State is lost. Moving a widget between parents is the job of GlobalKey.
Keys on only some siblings
You do not need a key on every child of a Column. A fixed header or footer does not move, so it matches by position and type without help:
Column(
children: [
const Text('Counters'),
for (final label in _labels)
CounterTile(key: ValueKey(label), label: label),
const Divider(),
],
)Flutter matches keyed and unkeyed children together without trouble. The keyed ones are found by key, and the others are matched by position and type. Put keys on the children that can be reordered, inserted or removed, and skip the rest.
Be careful when you insert an unkeyed child before keyed ones. Unkeyed children shift position, so their State can attach to a different widget of the same type. If a stateful unkeyed widget lives in a part of the list that changes, give it a key too.
Checklist before you add a key
- Find the parent whose children can be reordered, inserted or removed.
- Look at what that parent holds directly. That widget is the item root.
- Choose a key from something stable about the item, such as an ID, not an index that changes when the list changes.
- Put the key on the item root, at the place where you construct it.
- Test by reordering the list with state set on each item, as the demo does.
Exercise
A list is built as Column(children: [for (final u in users) Padding(padding: const EdgeInsets.all(8), child: UserCard(key: ValueKey(u.id), user: u))]). Each UserCard is a StatefulWidget with a local expanded/collapsed flag. After the list is sorted by name, some cards lose their expanded state and others keep it. Why does this happen, and how do you fix it?
Show answer
The Column holds Padding widgets, which have no key, so it matches them by position and type. Each Padding Element is reused and then compares its old UserCard key with the new one. When the keys differ, the old Element and State are discarded and a fresh State is created. Cards that happen to stay at the same position keep their state. Fix it by moving the key to the Padding: Padding(key: ValueKey(u.id), padding: ..., child: UserCard(user: u)). The key can stay on UserCard as well, but it is no longer what makes the list work.