Sub topic 6
Fixing the reorder problem with ValueKey
This chapter shows how to fix the reorder bug with ValueKey. It covers what the key changes in Flutter's matching, how to choose the value, and where ValueKey breaks down. It assumes you know the Widget, Element and State relationship, and the matching rule that compares runtimeType and key. It also assumes you have seen the symptom: after a reorder, the State of a stateful widget stays at its old position while the widgets move.
The bug in one example
CounterTile is a stateful widget that owns a tap counter. The counter lives in its State, not in the widget's fields.
import 'package:flutter/material.dart';
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++),
);
}
}A list of three tiles, labelled A, B and C, is reversed to C, B, A. Without keys, Flutter compares the new widgets with the old Elements slot by slot. Slot 0 held a CounterTile and now gets a CounterTile, so the types match and the keys are both null. Flutter reuses that Element and its State, then hands it the new widget with label C. The label changes, but the counter belongs to the State, so it stays where it was. A tile you tapped five times under A now shows five taps under C.
The fix: give each item a ValueKey
A ValueKey<T> wraps a value and compares equal to another ValueKey that wraps an equal value. Pass one that identifies the item, not its position.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: Scaffold(body: TileList())));
}
class TileList extends StatefulWidget {
const TileList({super.key});
@override
State<TileList> createState() => _TileListState();
}
class _TileListState extends State<TileList> {
List<String> _labels = ['A', 'B', 'C'];
void _reverse() {
setState(() => _labels = _labels.reversed.toList());
}
@override
Widget build(BuildContext context) {
return Column(
children: [
for (final label in _labels)
CounterTile(key: ValueKey(label), label: label),
TextButton(onPressed: _reverse, child: const Text('Reverse')),
],
);
}
}
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++),
);
}
}Run it, tap A three times and B once, then press Reverse. The counts follow their labels. Delete key: ValueKey(label) and run it again to see the counters stay in place while the labels swap.
Why the key changes the outcome
Matching is no longer purely positional once the children carry keys. Flutter builds a lookup of the old children by key. For each new child, it asks whether an old Element has the same runtimeType and an equal key, wherever that Element sat before.
In the reversed list, the new first child has key ValueKey('C'). The old Element that held ValueKey('C') was in slot 2, and it is reused for slot 0. Its State moves with it, and so does the counter. The RenderObject for that item is repositioned instead of being rebuilt from scratch.
Keys do not change the lifecycle of State. They only change which old Element a new widget is paired with. When no old Element matches, Flutter creates a new Element and calls createState. When an old keyed Element has no match in the new list, it is unmounted and its State is disposed.
How ValueKey compares
ValueKey<T> equality requires two things:
- The two objects have the same runtime type, including the type argument.
- Their
valuefields are equal under==.
The second point means ValueKey<int>(1) and ValueKey<String>('1') are different keys. It also means the value's == and hashCode matter. Strings, ints and enums behave well. A custom class that doesn't override == compares by identity, which is the right behavior only if you keep the same instance.
void main() {
print(const ValueKey<int>(1) == const ValueKey<int>(1)); // true
print(const ValueKey<int>(1) == const ValueKey<num>(1)); // false
print(const ValueKey<String>('a') == const ValueKey<String>('a')); // true
}Type inference usually picks the right argument. ValueKey(label) with a String becomes ValueKey<String>. A mismatch appears when one place builds the key from an int variable and another place builds it from a num variable, so keep the type consistent.
The Key factory constructor, Key('a'), creates a ValueKey<String>. It is shorthand, and ValueKey is clearer when you read the code later.
Choosing the value
The value has to satisfy two rules.
- It is unique among siblings. Two siblings with equal keys make Flutter throw a "Duplicate keys found" error in debug mode.
- It is stable for the lifetime of the item. If the value changes, the key changes, and Flutter treats the widget as a new item. The old State is discarded.
| Candidate value | Unique among siblings | Stable across reorders | Verdict |
|---|---|---|---|
| Database or server id | Yes | Yes | Best choice |
| A label, when labels are unique | Yes, by assumption | Yes, until renamed | Fine for demos, risky when users can edit it |
| List index | Yes | No | Reproduces the original bug |
| `DateTime.now()` or a random number created in `build` | Yes | No | New key every frame, State is lost on each rebuild |
A key built from the index is the common mistake. ValueKey(index) identifies a position. That is exactly what unkeyed matching already does, so the bug stays. It also makes the code look as if it handled the problem.
A list with ids, inserts and removals
Reordering is one case. Insertions and removals at the start of a list produce the same problem, because every later item shifts by one slot. Here is a list backed by model objects with ids.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: Scaffold(body: TaskList())));
}
class Task {
const Task(this.id, this.title);
final int id;
final String title;
}
class TaskList extends StatefulWidget {
const TaskList({super.key});
@override
State<TaskList> createState() => _TaskListState();
}
class _TaskListState extends State<TaskList> {
final List<Task> _tasks = [
const Task(1, 'Write'),
const Task(2, 'Test'),
const Task(3, 'Ship'),
];
int _nextId = 4;
void _addFirst() {
setState(() => _tasks.insert(0, Task(_nextId, 'Task $_nextId')));
_nextId++;
}
void _removeFirst() {
if (_tasks.isEmpty) return;
setState(() => _tasks.removeAt(0));
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
TextButton(onPressed: _addFirst, child: const Text('Add first')),
TextButton(
onPressed: _removeFirst,
child: const Text('Remove first'),
),
],
),
Expanded(
child: ListView.builder(
itemCount: _tasks.length,
findChildIndexCallback: (Key key) {
final valueKey = key as ValueKey<int>;
final index = _tasks.indexWhere((t) => t.id == valueKey.value);
return index == -1 ? null : index;
},
itemBuilder: (context, index) {
final task = _tasks[index];
return CounterTile(key: ValueKey(task.id), label: task.title);
},
),
),
],
);
}
}
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++),
);
}
}Tap Test twice, then press Add first. A new tile appears at the top and Test keeps its two taps. Press Remove first twice and Test still keeps them.
The findChildIndexCallback argument is specific to lazy lists. A ListView.builder only builds the visible children, so it cannot scan all keys. When the list changes, the callback tells it where an existing keyed child has moved. Without it, builder lists still work, but Flutter can't preserve State for off-screen items as cheaply. The callback should return null when the key's item no longer exists.
Edge cases
- Keys on stateless widgets. A key on a
StatelessWidgetis allowed, but there is no State to preserve. It only matters when the stateless widget has stateful descendants. Which widget should carry the key is covered in the next chapter. - Mixed keyed and unkeyed siblings. Flutter matches the keyed ones by key and the unkeyed ones by position and type. Mixing is legal, but it makes the result hard to predict. Key every item in a dynamic collection.
- Editing the identifying value. If
ValueKey(task.title)is used and the user renames the task, the key changes and the tile loses its State. Use an id that outlives edits. - Equal values in different lists. Keys only need to be unique among siblings, which are children with the same parent. Two separate columns may both use
ValueKey('A')without conflict. - Items that change type. If the widget at a key changes
runtimeType, the Element is not reused even though the key matches.
Debugging checklist
If state still lands on the wrong item after adding keys, check these points in order.
- Is the key on the topmost widget that the collection builds for each item? A key placed deeper inside the item doesn't identify the item among its siblings.
- Is the value unique? Look for the duplicate keys error in the debug console.
- Is the value stable? Print it in
buildand check it doesn't change across rebuilds. - Is the
Statereally owned by the keyed widget? State held by a parent isn't affected by keys on its children. - Do all the items have the same key type argument? A
ValueKey<int>next to aValueKey<num>never matches.
Exercise
A screen shows a list of chat drafts. Each draft is a StatefulWidget that owns a TextEditingController, and the list is sorted by last edit time, so editing one draft moves it to the top. A developer writes DraftTile(key: ValueKey(index), draft: drafts[index]). After an edit, the text typed into one draft appears under a different draft. Why does this happen, and what should the key be?
Show answer
The key ValueKey(index) identifies a slot, not a draft. When sorting moves a draft to the top, the new widget at index 0 has the same key as the old widget at index 0, so Flutter reuses the old Element and State, including the controller and its text, and only swaps in the new draft data. The State stays at its position while the data moves. Use a stable per-draft identifier, such as ValueKey(draft.id), where the id is assigned when the draft is created and does not change when the draft is edited or moved.
Exercise
Which of these two expressions are equal, and why? (a) ValueKey<int>(7) and ValueKey<int>(7). (b) ValueKey<int>(7) and ValueKey<String>('7'). (c) ValueKey<int>(7) and ValueKey<num>(7).
Show answer
(a) Equal: same runtime type and equal values. (b) Not equal: the type arguments and the values differ. (c) Not equal: the values are the same number, but ValueKey<int> and ValueKey<num> have different runtime types, and the comparison includes the type.
Exercise
In the TaskList example, remove the ValueKey from CounterTile but keep the add and remove buttons. Tap the second tile twice, press Add first, and describe what you see and why.
Show answer
The new tile appears on top with a count of 0, and the count of 2 now shows on the tile that sits in the second slot, which is the first task's tile, not the tapped one. Without keys, Flutter pairs new widgets with old Elements by position. The Element in slot 1 keeps its State with count 2 and receives the label of the task that moved into slot 1. The extra tile at the end of the list gets a new Element and State with count 0, and the counts end up under the wrong labels.