Sub topic 8
Keys: keeping State attached to the right widget
This chapter assumes you know basic Dart and can build simple Flutter apps with StatelessWidget, StatefulWidget, Row, and Column. You should also understand that a State object belongs to a StatefulElement, not directly to a widget configuration.
Why keys matter
Flutter rebuilds widgets by comparing the old widget tree with the new one. For sibling widgets, Flutter normally matches children by position and runtime type. When a match succeeds, the existing element and its State are reused.
This becomes a problem when stateful children move. Consider two counters labeled A and B. If the list changes from [A, B] to [B, A], unkeyed children may keep their positions while their labels change. The counter value that belonged to A can now appear beside B.
A key gives a widget an identity among its siblings. Flutter can then move the existing element, along with its State, to the matching position.
import 'package:flutter/material.dart';
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 ListTile(
title: Text(widget.label),
trailing: Text('$taps'),
onTap: () => setState(() => taps++),
);
}
}
class SwapPage extends StatefulWidget {
const SwapPage({super.key});
@override
State<SwapPage> createState() => _SwapPageState();
}
class _SwapPageState extends State<SwapPage> {
var labels = ['A', 'B'];
@override
Widget build(BuildContext context) {
return Column(
children: [
ElevatedButton(
onPressed: () => setState(() {
labels = labels.reversed.toList();
}),
child: const Text('Swap'),
),
for (final label in labels)
Tile(key: ValueKey(label), label: label),
],
);
}
}
void main() => runApp(
const MaterialApp(home: Scaffold(body: SwapPage())),
);ValueKey(label) makes each tile identifiable by its label. After swapping, the element containing A moves with A and retains its counter value.
Choosing and using keys
| Key | Typical use |
|---|---|
| `ValueKey<T>` | Stable value such as an ID |
| `ObjectKey` | Identity of a particular object |
| `UniqueKey` | Force a distinct identity each time |
| `GlobalKey` | Access or move a widget across distant parts of the tree |
Use a stable key from the data model, such as a database ID. Do not use the list index when items can be inserted, removed, or reordered. A UniqueKey also prevents reuse, so it discards existing state on each replacement.
Keys only distinguish siblings under the same parent. They do not make two unrelated widgets globally identical. GlobalKey has extra bookkeeping and should be reserved for cases that need cross-tree identity or access to a widget's state.
Exercise
A reorderable list loses each item's text-field contents. What should you check first?
Show answer
Give each stateful row a stable key based on the item's identity, not its current list index.