Sub topic 2
What keys are: LocalKey and GlobalKey
This chapter assumes you know Dart classes, StatelessWidget and StatefulWidget, setState, and basic layout with Column and ListTile.
Flutter rebuilds the widget tree on every frame, but it reuses the Element and State objects where it can. For each child, Flutter compares the new widget with the widget in the same slot from the previous frame. A match needs the same runtimeType and the same key. Position alone is often enough. When a list changes order, a key tells Flutter which widget is which.
A key is an object passed to a widget's constructor. Keys come in two families:
| Key family | Scope | Typical use |
|---|---|---|
| `LocalKey` (for example `ValueKey`) | Only among siblings under the same parent | Identify list items |
| `GlobalKey` | Whole tree | Reach a `State` or move a widget between parents |
Fixing the reorder problem with ValueKey
The following program shows a list of counters. Tap a counter to increase it, then press Reverse. Without a key, each counter keeps its position, so the labels swap while the counts stay behind. Adding key: ValueKey(label) makes each counter follow its label.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: 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'];
@override
Widget build(BuildContext context) {
return Column(
children: [
for (final label in _labels)
CounterTile(key: ValueKey(label), label: label),
TextButton(
onPressed: () =>
setState(() => _labels = _labels.reversed.toList()),
child: const Text('Reverse'),
),
],
);
}
}Putting the key on the right widget
Place the key on the topmost widget that Flutter compares in the list. This is the direct child of the parent that builds the list, not a widget nested inside it.
- Put the key on the item's outermost widget, such as the
ListTileorCard. - Do not put the key on an inner
TextorPaddingchild. Flutter then compares the outer keyless widget, and the reorder bug returns. - Use a stable value, such as an ID from your data. Do not create a new key in
build, because each rebuild then looks like a new widget.
Correct: ListTile(key: ValueKey(item.id), ...)
Wrong: ListTile(title: Text(item.name, key: ValueKey(item.id)))> Not a blockquote: the callout below carries the warning.
Exercise
In the TileList example, you give each CounterTile a ValueKey built from its label. A colleague instead writes key: UniqueKey() inside build. What happens to a counter's count when you press Reverse?
Show answer
The count resets to zero on every rebuild. UniqueKey creates a new key each time build runs, so Flutter never matches the old State to the new widget.