Sub topic 12
Pitfalls: duplicate keys, keys created in `build`, and `GlobalKey` cost
This chapter assumes that you know basic Dart, StatefulWidget, setState, and common widgets such as Column and ListView. The key rule is that Flutter matches a new widget with an existing Element by runtime type and key. A mistake in either the key's value or its lifetime can make state disappear, move incorrectly, or prevent the widget tree from being built.
Duplicate keys
A LocalKey must be unique among the children of one parent. Two ValueKey<String>('item') objects are equal because they contain the same value, so they cannot identify two sibling widgets.
Column(
children: const [
Text('First', key: ValueKey<String>('item')),
Text('Second', key: ValueKey<String>('item')), // Error
],
)Flutter normally reports a duplicate-key assertion during development. The problem is not that the keys were created as two separate Dart objects. ValueKey compares values. If two sibling items have the same database ID, slug, or other identifier, they have the same problem.
The uniqueness scope matters:
| Key type | Required uniqueness | Typical purpose |
|---|---|---|
| `ValueKey` | Siblings under the same parent | Identify an item by a stable value |
| `ObjectKey` | Siblings under the same parent | Identify an item by object identity |
| `GlobalKey` | The entire widget tree | Reach `State` or move a subtree |
Do not use an index as a key when the collection can insert, remove, or reorder items. An index identifies a position, not an item. It therefore preserves state at that position and can associate the state with a different record.
Keys created in `build`
Creating a ValueKey in build is normally safe:
ValueKey(product.id)The key object may be new, but equal ValueKey instances compare equal when product.id is unchanged. The important part is that the value remains stable and uniquely identifies the item.
Creating a UniqueKey in build has the opposite effect. Every call creates a key that compares unequal to every previous key. Flutter treats the widget as new, disposes the old State, and creates another one.
class ResettingPanel extends StatelessWidget {
const ResettingPanel({super.key});
@override
Widget build(BuildContext context) {
return const CounterPanel(key: UniqueKey());
}
}
class CounterPanel extends StatefulWidget {
const CounterPanel({super.key});
@override
State<CounterPanel> createState() => _CounterPanelState();
}
class _CounterPanelState extends State<CounterPanel> {
int count = 0;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => setState(() => count++),
child: Text('Taps: $count'),
);
}
}If ResettingPanel rebuilds, CounterPanel receives a new identity and its count resets. Use UniqueKey when forcing replacement is intentional, such as resetting an animation or form. Otherwise, use a stable value or omit the key.
`GlobalKey` cost and misuse
A GlobalKey provides capabilities that local keys do not. Code can use currentState or currentContext, and Flutter can move the keyed subtree between parents during one frame. Those capabilities require extra bookkeeping.
Moving a GlobalKey subtree can deactivate its descendants. Descendants that depend on inherited widgets may need to rebuild. Large subtrees therefore make global-key reparenting more expensive than ordinary local matching.
Create a GlobalKey once and keep it in a long-lived owner, usually a State object:
class SettingsPage extends StatefulWidget {
const SettingsPage({super.key});
@override
State<SettingsPage> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
final formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: ElevatedButton(
onPressed: () => formKey.currentState?.validate(),
child: const Text('Validate'),
),
);
}
}Creating this key inside build loses the reference on every rebuild and defeats its purpose. Reusing one GlobalKey in two mounted locations is also invalid. Prefer callbacks, lifted state, or a controller when they can solve the problem without exposing a subtree's State.
Exercise
A reorderable list uses UniqueKey() for every row inside build, and each row contains a text field. Why do the fields lose their contents after any parent rebuild, and what should replace the key?
Show answer
Each rebuild creates different keys, so Flutter discards every row's old State. Use a stable ValueKey based on the row's unique ID, or lift the text state to the list's owner when the data should outlive each row.