Sub topic 12
Pitfalls: duplicate keys, keys created in build, and GlobalKey cost
This chapter assumes you know the matching rule (a widget reuses an Element and its State when runtimeType and key both match), the reorder problem, and how ValueKey, ObjectKey, UniqueKey and GlobalKey are used. Here you will learn how each of them goes wrong in practice. Most key bugs fall into three groups: keys that collide, keys that change when they should not, and GlobalKeys used where a cheaper tool would do.
Pitfall 1: duplicate keys among siblings
A LocalKey must be unique among the children of the same parent. It does not need to be unique across the whole app. Two ValueKey('A') in different Columns are fine. Two in the same Column are not.
In debug builds, Flutter throws an assertion when it finds two siblings with equal keys. The message begins with Duplicate keys found. In release builds the assertion is stripped, so you get no error. Flutter then has two widgets claiming one identity, and state may attach to the wrong one. Do not treat a clean release run as proof that your keys are unique.
Duplicates usually come from using a display value as an identity:
import 'package:flutter/material.dart';
class Todo {
const Todo(this.id, this.title);
final int id;
final String title;
}
class TodoColumn extends StatelessWidget {
const TodoColumn({super.key, required this.todos});
final List<Todo> todos;
@override
Widget build(BuildContext context) {
return Column(
children: [
for (final todo in todos)
// Wrong: two todos titled "Milk" produce two equal keys.
// CounterTile(key: ValueKey(todo.title), label: todo.title),
//
// Right: the id identifies the todo, the title only describes it.
CounterTile(key: ValueKey(todo.id), label: todo.title),
],
);
}
}CounterTile is the stateful tile from the running example at the start of this tutorial. As before, wrap the result in a Scaffold so ListTile has a Material ancestor.
Three related mistakes cause the same kind of trouble:
- Using the list index as the key.
ValueKey(index)is unique, but it names a position, not an item. After a reorder, each key still sits at the same position, so you get the original reorder bug with extra ceremony. Index keys are fine only for lists that never reorder or have items inserted or removed in the middle. - Mixing types.
ValueKey<int>(1)andValueKey<String>('1')are different keys. This is not a collision, but it surprises people who convert ids between types halfway through a build method. - Keying by a whole entity.
ValueKey(todo)compares with==. IfTododoes not override==, a refetch from the server produces new instances, the keys no longer match, and every row loses its state. IfTodooverrides==to compare all fields, editing a title changes the key and also resets state. A stableidavoids both problems.
Pitfall 2: keys created in build
A key only helps if the key for the same item is equal from one frame to the next. Anything that produces a new identity on every build defeats it, because the matching rule then sees "different key" and throws the old Element and State away.
The classic case is UniqueKey() inside build:
// Wrong: a new UniqueKey on every build, so the tile's State is discarded
// each time this widget's parent rebuilds.
Widget build(BuildContext context) {
return CounterTile(key: UniqueKey(), label: 'A');
}Each UniqueKey equals only itself. A new one on every build means the tile is rebuilt from scratch every time, which loses its counter, its focus, and any running animation. It is also slower than not using a key at all.
UniqueKey is meant for the opposite situation: you want a fresh identity once, deliberately. Keep that identity somewhere that survives rebuilds, such as a State field. Or, more readably, key on a value you change on purpose:
import 'package:flutter/material.dart';
class ResettableTile extends StatefulWidget {
const ResettableTile({super.key});
@override
State<ResettableTile> createState() => _ResettableTileState();
}
class _ResettableTileState extends State<ResettableTile> {
int _generation = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
// The key stays equal across rebuilds and changes only when the
// button increments _generation. That discards the tile's State once.
CounterTile(key: ValueKey(_generation), label: 'A'),
TextButton(
onPressed: () => setState(() => _generation++),
child: const Text('Reset'),
),
],
);
}
}This pattern is a clean way to reset a subtree's state without writing reset logic inside it.
The same mistake appears in quieter forms:
| Code in `build` | Why the key changes every frame |
|---|---|
| `UniqueKey()` | Each instance equals only itself. |
| `GlobalKey()` | Each instance is a distinct key, so the State is lost and the registry is churned. |
| `ObjectKey(Todo(...))` | `ObjectKey` compares with `identical`, and a freshly built object is never identical to the previous one. |
| `ValueKey([a, b])` | `List` uses identity equality, so a new list is a new key. |
| `ValueKey(DateTime.now())` | The value differs on every call. |
The fix is the same in every row. Derive the key from stable data, or create it once in a State field.
Pitfall 3: GlobalKey cost and misuse
A GlobalKey is unique across the whole app, not only among siblings. Flutter enforces this with a registry owned by the BuildOwner. Every mounted GlobalKey is recorded in it, and the framework has to check it when widgets are mounted, unmounted, or moved. The Flutter documentation says global keys are relatively expensive, and recommends a Key, ValueKey, ObjectKey or UniqueKey when you do not need what a GlobalKey offers. That means reaching a State from outside, or moving a subtree to a new parent without losing its state.
Create it once
A GlobalKey must outlive rebuilds. Create it in a State field, as the form example in this tutorial does. Do not create it in build, and do not put it as a field on a StatelessWidget, because that widget object is recreated whenever its parent rebuilds.
import 'package:flutter/material.dart';
class SaveForm extends StatefulWidget {
const SaveForm({super.key});
@override
State<SaveForm> createState() => _SaveFormState();
}
class _SaveFormState extends State<SaveForm> {
// Created once per State object and reused by every build.
final _formKey = GlobalKey<FormState>();
void _save() {
final form = _formKey.currentState;
// currentState is null if the Form is not currently in the tree.
if (form != null && form.validate()) {
// All fields are valid.
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (v) => (v == null || v.isEmpty) ? 'Required' : null,
),
ElevatedButton(onPressed: _save, child: const Text('Save')),
],
),
);
}
}Null results and timing
currentState, currentContext and currentWidget are all null when no widget with that key is mounted. This happens before the first frame, after the widget is removed, or when the widget sits in a branch that is not built, such as an offscreen lazy list item. Writing _key.currentState! works in a happy-path demo and crashes in a callback that fires at the wrong moment. Check for null, or confirm that the call can only happen while the widget is mounted.
One place at a time
A given GlobalKey may be used by only one widget in the tree at a time. If two widgets use it in the same frame, Flutter reports Multiple widgets used the same GlobalKey. This is easy to hit by accident:
- You share one key between two copies of a screen, such as a phone layout and a tablet layout built side by side.
- You build a list in which every row uses the same key instance, instead of one key per row.
- A page is pushed twice and both instances use a key held in a global variable.
Moving a keyed subtree is the feature, but it has a timing rule. The widget must disappear from the old place and appear in the new one within the same frame. If it is gone for a frame, its State is disposed. When the move works, Flutter deactivates the old Element, reuses it in the new location, and runs didChangeDependencies on it.
Cost in lists
One GlobalKey for a form is cheap. A GlobalKey per row in a list of thousands is wasteful. Each row adds to the registry, the keys are retained as long as the rows are mounted, and the design invites other code to reach into row State from outside. For list items, a ValueKey on an id gives you state preservation without any of this.
Reaching in is a design cost
_key.currentState!.doSomething() couples the caller to the private shape of another widget. It also bypasses the normal data flow that makes Flutter code easy to follow. Prefer these options, in order:
- Pass data down and callbacks up.
- Pass a controller object, as
TextEditingControllerandScrollControllerdo. - Use a
GlobalKeyonly when the target is a framework class that is designed for it, such asFormState,NavigatorState,ScaffoldStateorScaffoldMessengerState, or when you must move a subtree between parents.
A short checklist for review
When you read a pull request that adds keys, ask these questions in order:
- Is the key on the topmost widget of each item in the collection?
- Does its value come from a stable identity field, not a title, an index or a timestamp?
- Is the key built from data or held in a
Statefield, never created fresh inbuild? - Can two siblings ever produce equal keys, for example from duplicated data?
- If it is a
GlobalKey, is it really needed, and does everycurrentStateaccess handlenull?
Exercises
Exercise
A list of CounterTiles is built with key: ValueKey(item.name). A user adds a second item named "Milk". In a debug build the app throws an assertion. In a release build there is no error, but tapping one "Milk" tile sometimes changes the other tile's counter. Explain both observations and give the fix.
Show answer
In debug builds Flutter asserts that sibling keys are unique, and two ValueKey('Milk') are equal, so it reports "Duplicate keys found". Release builds strip the assertion, so nothing is reported. The matching rule still sees two widgets with the same type and key, so state can attach to the wrong one after the list is updated. The fix is to key on a stable unique identifier, such as ValueKey(item.id), and use item.name only for display.
Exercise
A teammate writes final formKey = GlobalKey<FormState>(); at the top of a StatelessWidget's build method and passes it to a Form. Validation works on the first tap, but text typed into the fields disappears whenever the parent rebuilds. What is wrong, and how do you fix it?
Show answer
A new GlobalKey is created on every build. The Form therefore has a different key each time, so Flutter cannot match it to the previous Element and discards the FormState and the fields below it, which loses the typed text. The key also churns the global registry. Convert the widget to a StatefulWidget and create the key once as a State field (final _formKey = GlobalKey<FormState>();). Use _formKey.currentState with a null check when validating.