Sub topic 5
What keys are: LocalKey and GlobalKey
This chapter assumes you know how Flutter builds the Widget, Element and State objects, how Flutter matches a new widget to an existing Element, and why reordering stateful widgets can leave state behind. It covers what a Key is, how the class hierarchy is organized, and the one rule that separates the two branches: how far a key's uniqueness extends.
A key is an identity label
A Key is an object you pass to a widget's key parameter. Flutter doesn't draw it or give it any behavior. It exists so the framework can compare it. During a rebuild, Flutter looks at the old widget attached to an Element and the new widget in the same slot. It asks Widget.canUpdate whether the Element can be reused:
static bool canUpdate(Widget oldWidget, Widget newWidget) {
return oldWidget.runtimeType == newWidget.runtimeType &&
oldWidget.key == newWidget.key;
}If both checks pass, the Element keeps its State and receives the new widget configuration. If either fails, the old Element and its State are discarded and a new pair is created. A key is therefore the part of the check you control. Two widgets of the same type are interchangeable unless their keys differ.
When you don't pass a key, key is null. Two null keys are equal, so unkeyed siblings of the same type match purely by position. That behavior causes the reorder problem from the previous chapter.
Keys are immutable and are compared with ==. How a key's == works is the main difference between key types.
The class hierarchy
All keys extend the abstract class Key. It has two direct branches, LocalKey and GlobalKey.
Key also has a factory constructor: Key('a') returns a ValueKey<String>('a'). It is a shortcut for the most common case, and the two forms compare as equal.
LocalKey: unique among siblings
A LocalKey only needs to be unique among the children of the same parent. Flutter uses it when it walks one parent's list of children and decides which old child lines up with which new child. It never compares a LocalKey against widgets under a different parent.
Two Columns can therefore each contain a child with ValueKey('a') without conflict. Within one Column, two children with equal keys cause a "Duplicate keys found" assertion error in debug mode.
The LocalKey subclasses differ in how they define equality:
| Key | Two keys are equal when | Typical use |
|---|---|---|
| `ValueKey<T>` | same `T` and `value == other.value` | Items with a stable ID or label |
| `ObjectKey` | `identical(value, other.value)` | Items represented by a model object |
| `UniqueKey` | never, except with itself | Forcing a fresh State |
| `PageStorageKey<T>` | same as `ValueKey<T>` | Saving scroll position and similar data |
Later chapters cover each one in detail. For now, remember that they all answer the same question for Flutter: "Is this the same logical child as before?"
Checking equality yourself
Equality rules are easy to get wrong, so it helps to test them. This test file checks the rules above. Run it with flutter test.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class Item {
Item(this.id);
final int id;
}
void main() {
test('LocalKey equality rules', () {
// Key('a') is a ValueKey<String>('a').
expect(const Key('a') == const ValueKey<String>('a'), isTrue);
// The type argument is part of the comparison.
expect(const ValueKey<int>(1) == const ValueKey<String>('1'), isFalse);
// ObjectKey compares by identity, not by ==.
final item = Item(1);
expect(ObjectKey(item) == ObjectKey(item), isTrue);
expect(ObjectKey(Item(1)) == ObjectKey(Item(1)), isFalse);
// UniqueKey is equal only to itself.
final unique = UniqueKey();
expect(unique == unique, isTrue);
expect(UniqueKey() == UniqueKey(), isFalse);
});
test('Widget.canUpdate uses runtimeType and key', () {
const a = Text('x', key: ValueKey('a'));
const sameKey = Text('y', key: ValueKey('a'));
const otherKey = Text('x', key: ValueKey('b'));
const otherType = SizedBox(key: ValueKey('a'));
expect(Widget.canUpdate(a, sameKey), isTrue);
expect(Widget.canUpdate(a, otherKey), isFalse);
expect(Widget.canUpdate(a, otherType), isFalse);
});
}The second test shows that the widget's contents don't matter. Text('x') and Text('y') with the same key are treated as the same logical widget, with a changed configuration.
GlobalKey: unique across the app
A GlobalKey must be unique across the entire widget tree, not just among siblings. Flutter keeps a registry that maps each active GlobalKey to the one Element currently using it. That registry gives a GlobalKey abilities a LocalKey doesn't have:
- Lookup from anywhere.
key.currentContext,key.currentWidgetandkey.currentStategive you theBuildContext, widget orStatethat currently holds the key, even from code outside that widget's subtree. - Moving a subtree. If a widget with a
GlobalKeydisappears from one parent and appears under a different parent in the same frame, Flutter moves the existing Element, with itsStateand children, instead of rebuilding it. ALocalKeycan't do this, because it is only compared within one parent.
The key's type argument controls what currentState returns. GlobalKey<T extends State<StatefulWidget>> gives you a typed State, so you can call its public methods.
A GlobalKey in practice
This app lets a button outside the Counter call a method on the Counter's State:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: CounterPage()));
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => CounterState();
}
// Public so that GlobalKey<CounterState> can name it.
class CounterState extends State<Counter> {
int count = 0;
void increment() => setState(() => count++);
@override
Widget build(BuildContext context) => Text('Count: $count');
}
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
// Created once, in State, not in build.
final _counterKey = GlobalKey<CounterState>();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Counter(key: _counterKey)),
floatingActionButton: FloatingActionButton(
onPressed: () => _counterKey.currentState?.increment(),
child: const Icon(Icons.add),
),
);
}
}Note two details. The key is stored in a final field of the State, so the same key object is reused on every build. And currentState is nullable. It is null if no widget is currently using the key, for example before the first frame or after the widget has been removed.
Choosing a scope
The scope is the main design difference. The table summarizes it:
| Question | LocalKey | GlobalKey |
|---|---|---|
| Must be unique among | Siblings under one parent | The whole app |
| Flutter compares it when | Matching a parent's old and new children | Matching children, and also across parents |
| Can reach `State` from outside | No | Yes |
| Can move a subtree between parents | No | Yes |
| Cost | Very low | Registry bookkeeping, and a stricter uniqueness rule |
Use a LocalKey by default, whenever your goal is "keep this item's state attached to this item inside a list or other group of children". Use a GlobalKey only when you need one of the two special abilities. The next chapters follow this order: ValueKey first, then ObjectKey and UniqueKey, PageStorageKey and GlobalKey, and the pitfalls of each.
Common mistakes at this level
- Assuming a key changes appearance or behavior. A key does nothing by itself. It only changes the result of
canUpdate. - Using a
GlobalKeywhen aValueKeywould do. AGlobalKeyin a reorderable list works, but it adds registry overhead and a global uniqueness rule you then have to maintain. - Creating a
GlobalKeyinsidebuild. Each build produces a new key object, so Flutter sees a different key every time and recreates the State. Store the key in theStateobject, as in the example above. - Reading
currentState!too early. Before the widget is mounted,currentStateisnull, and the!operator throws. - Giving siblings equal keys. Two children of one parent with equal keys trigger a duplicate-key assertion in debug mode, so make the key's value truly unique within that group.
Exercise
A Column contains Counter(key: ValueKey(1)), and a different Column elsewhere in the app also contains Counter(key: ValueKey(1)). Is this allowed? What would change if both used GlobalKey instead, built from the same GlobalObjectKey(1)?
Show answer
It is allowed. ValueKey is a LocalKey, so it only needs to be unique among siblings under one parent, and the two Columns are different parents. With GlobalObjectKey(1) on both, the keys are equal and must be unique across the whole tree, so two widgets using it at the same time would trigger a duplicate GlobalKey error.
Exercise
Predict the result of Widget.canUpdate(const Text('a', key: ValueKey(1)), const Text('b', key: ValueKey<String>('1'))). Explain why.
Show answer
It returns false. Both widgets are Text, so the runtimeType check passes. But ValueKey<int>(1) and ValueKey<String>('1') are not equal, because the type argument is part of the comparison, so the key check fails. Flutter would discard the old Element and its State.