Sub topic 6
Fixing the reorder problem with ValueKey
This chapter assumes that you can write basic Dart, build StatelessWidget and StatefulWidget classes, use setState, and work with Column, ListView, and ListTile.
A reorder bug appears when a collection contains stateful widgets. Flutter may preserve a State object, but attach it to a different item after the collection changes order.
Why state stays in the wrong position
Flutter compares the new widget tree with the previous tree. For children under the same parent, it normally looks at:
- The widget's runtime type.
- The widget's key, if it has one.
- The widget's position among its siblings.
If two widgets have the same type and no keys, position becomes the important identity. Consider three CounterTile widgets:
Position 0: CounterTile for A, count 2
Position 1: CounterTile for B, count 0
Position 2: CounterTile for C, count 1After reversing the labels, the positions still contain the same State objects:
Position 0: CounterTile for C, count 2
Position 1: CounterTile for B, count 0
Position 2: CounterTile for A, count 1The counters stayed with positions instead of following their logical items.
Give each item a ValueKey
ValueKey<T> is a local key whose identity comes from a value. Use a value that uniquely and stably identifies the item, such as a database ID.
The key belongs on the top-level widget that represents one item in the collection:
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: TileList()));
}
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 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 Scaffold(
appBar: AppBar(title: const Text('ValueKey example')),
body: Column(
children: [
for (final label in _labels)
CounterTile(
key: ValueKey<String>(label),
label: label,
),
TextButton(
onPressed: _reverse,
child: const Text('Reverse'),
),
],
),
);
}
}When the list reverses, Flutter finds the old CounterTile with ValueKey('A') and reuses its state for the new position of A. The counter follows A.
| Key choice | Identity comes from | Suitable example |
|---|---|---|
| `ValueKey<String>(id)` | A value | Stable item ID |
| `ValueKey<int>(id)` | A value | Numeric database ID |
| No key | Usually position | Items with no local state |
Choose a stable value
A key value must be unique among the relevant siblings. It should also remain the same while the item represents the same logical object.
A label works only if labels are unique and do not change unexpectedly. Prefer an immutable ID when available:
CounterTile(
key: ValueKey<int>(item.id),
label: item.name,
)Do not use the list index as the key when items can be inserted, removed, or reordered. The index identifies a position, which is exactly the source of this problem.
Exercise
Exercise
A reorderable list displays products with a stable product.id. Where should you put the key, and which key should you use?
Show answer
Put ValueKey(product.id) on the top-level widget that represents each product, such as ProductTile(key: ValueKey(product.id), product: product).