Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 73 ยท Widgets and the widget tree

Keys and Widget Identity

Learn when Flutter keys matter: how elements match widgets, why reordering a list loses state, and how to use ValueKey, ObjectKey, UniqueKey and GlobalKey correctly.

Most Flutter code never needs a key, and then one day a list item keeps the wrong text after you delete another item, or a checkbox jumps to a different row after sorting. Those bugs come from one question the framework has to answer after every rebuild: which old widget does this new widget correspond to? Keys are how you answer it explicitly.

From the three trees you know that an element is reused when the new widget has the same type and the same key. This lesson shows the situations where "same type" is not enough, which key class to pick, and what GlobalKey is for. It also builds on StatefulWidget and setState, because the bugs only appear when there is state to lose.

Real vs stand-in. The Dart is real Flutter code, read-only here. The reconciliation examples are JavaScript stand-ins that follow the same rule the framework uses for children of a multi-child widget such as Column or Row.

What is a key?

A name tag It tells Flutter which widget is which.
Matching Type plus key decides element reuse.
1 / 2

Why identity matters: the reorder bug

A widget's position in a list is its default identity. Without keys, Flutter pairs old and new children by index, checking only the type. Consider a list of stateful tiles, where each remembers whether it is checked:

DART
class Tile extends StatefulWidget {
  const Tile({super.key, required this.title});
  final String title;

  @override
  State<Tile> createState() => _TileState();
}

class _TileState extends State<Tile> {
  bool _checked = false;

  @override
  Widget build(BuildContext context) {
    return CheckboxListTile(
      title: Text(widget.title),
      value: _checked,
      onChanged: (value) => setState(() => _checked = value!),
    );
  }
}

If the parent shows [Tile('Milk'), Tile('Eggs'), Tile('Rice')], you check "Milk", then delete it, the new list is [Tile('Eggs'), Tile('Rice')]. By index, element 0 (which holds _checked = true) is paired with the new first widget, now Eggs. The title updates (it comes from the widget), but the checked flag lives in the State, and the State stayed. Now "Eggs" is checked. That is the bug.

The fix is to give each tile a key that is stable for the data it represents:

DART
ListView(
  children: [
    for (final item in items)
      Tile(key: ValueKey(item.id), title: item.title),
  ],
)

Now the framework matches each new widget with the old element carrying the same key. Deleting "Milk" removes exactly its element, and "Eggs" keeps its own state.

Stand-in: reconciliation with and without keys

The two functions below implement the matching rule. byIndex mimics no keys. byKey looks up an old element with the same key first, falling back to nothing (a new element) when no match exists.

JS Delete the first item: index matching vs key matching

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Without keys, "Eggs" is wrongly checked because it inherited element #1 (the old "Milk" element). With keys, element #1 is dropped and "Eggs" keeps its own element #2, unchecked, which is correct.

Keys and sorting

The same problem appears when you reorder items: without keys, State stays at the old positions while the widgets' fields move. This second stand-in shuffles the list and shows which element each title ends up with.

JS Reordering swaps titles but not state

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Without keys, the row that shows "Cai" still holds the text field content ("note") that belonged to "Ann". Real examples: text typed into a TextField, a scroll position, a running animation, or a Checkbox inside a stateful widget.

When you need a key (and when you do not)

You need keys when widgets of the same type sit next to each other in a collection that can be reordered, inserted into or removed from, and they carry state in their State objects. Typical places:

  • To-do lists, chat messages, shopping carts, draggable and dismissible lists (Gestures and input handling).
  • AnimatedSwitcher children that must be seen as different (ValueKey(currentPage)) so the transition runs.
  • Tabs or pages that must reset when an id changes.

You do not need keys for:

  • Stateless widgets with no internal state; they have nothing to lose, only to be rebuilt.
  • Static children that never change order.
  • Items in a ListView.builder: they are created lazily and mostly rebuilt as you scroll; still add a ValueKey when items carry state and the list can change.

Where to put the key: on the top widget of each item in the collection, the one that is a direct child of the list, not on a widget deep inside it.

Picking the right key class

  • ValueKey(value): two keys are equal when their values are equal (==). Best choice when your data has a stable id: ValueKey(todo.id). Never use the index or a value that changes.
  • ObjectKey(object): equal when the objects are identical. Use when no single field is unique but the object instance is, for example a combination of values in one record.
  • UniqueKey(): is never equal to any other key. Creating a new one in build makes a new element every rebuild, throwing away the State. Use it only deliberately, to force a reset, and never as a default.
  • PageStorageKey(value): lets scrollables and other widgets save and restore state (like scroll offset) across navigation.
  • GlobalKey: see next section.

A common anti-pattern is key: UniqueKey() in build "just to be safe". It destroys state and animation every rebuild, and makes the app slower.

GlobalKey: reaching into the tree

A GlobalKey is unique across the entire app, and gives you access to the widget's State or BuildContext from elsewhere. The best-known use is forms:

DART
final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: Column(children: [
    TextFormField(validator: (v) => v == null || v.isEmpty ? 'Required' : null),
    ElevatedButton(
      onPressed: () {
        if (_formKey.currentState!.validate()) {
          // submit
        }
      },
      child: const Text('Send'),
    ),
  ]),
)

A GlobalKey can also move a widget with its State to a different place in the tree (reparenting) without losing state, which is useful for video players or complicated widgets that switch layout between portrait and landscape.

Cautions: GlobalKeys are comparatively expensive, there can only be one widget with a given key in the tree at a time, and reaching into other widgets' State couples your code tightly. Prefer passing data and callbacks, or the state tools covered in Lifting state up and ValueNotifier. Keep a GlobalKey as a field of a State object (created once), never create one inside build. You will use it for forms in Forms and validation.

Common mistakes

  • Using the list index as a key (ValueKey(index)). It behaves like no key when items move.
  • Putting the key on the wrong widget, such as an inner Text instead of the item's root widget.
  • Duplicate keys among siblings. Flutter reports "Duplicate keys found" in debug mode. Keys must be unique among siblings.
  • Creating a GlobalKey in build. A new key each time means a new State each time.
  • Adding keys everywhere. They are a fix for a specific problem, not a style rule.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Without keys, how does Flutter match old and new children in a Column?

    With no keys, children are paired in order and an element is reused when the types match.
  2. 2. You show a list of stateful tiles that can be deleted. Which key is the best choice?

    A stable id identifies the data. UniqueKey in build resets state every time, and the index changes when items move.
  3. 3. What is a GlobalKey<FormState> mostly used for?

    A GlobalKey gives access to the State of a specific widget from anywhere with access to the key.
  4. 4. Which situation does NOT usually require a key?

    Static stateless children have no State to lose, so index matching is fine.

Summary

  • After a rebuild, Flutter reuses an element when the type and key match; without keys, children are matched by position.
  • Reordering, inserting or removing same-type stateful widgets without keys can attach State to the wrong item.
  • Use ValueKey(stableId) on the root widget of each collection item; use ObjectKey for identity of an instance and UniqueKey only to force a reset.
  • GlobalKey gives access to a widget's State and can reparent it, but is costly and should be created once, not in build.
  • Never use the index as a key, and never create keys inside build unless you intend a reset.

Next: BuildContext and InheritedWidget