Sub topic 10
GlobalKey: reaching State and moving widgets between parents
This chapter assumes you know the Widget, Element and State relationship, the matching rule (runtime type plus key), and how ValueKey fixes reordering inside one list. Here you will see what changes when a key is unique across the whole app instead of within one parent.
What makes a GlobalKey different
A LocalKey such as ValueKey only has to be unique among the children of one parent. Flutter compares keys only between siblings, so two different lists can both contain ValueKey('A') without conflict.
A GlobalKey has a wider rule. At any moment, at most one widget in the whole widget tree can use a given GlobalKey instance. The framework keeps a registry that maps each GlobalKey to the one Element currently using it. That registry gives you two abilities that local keys do not have:
- Reaching the Element, State or RenderObject of a widget from code that is outside that widget's subtree.
- Moving a widget, together with its whole subtree and State, to a different parent without losing that State.
The Element is the object that holds the State, so both abilities come from the same registry lookup.
Reaching State from outside the subtree
A GlobalKey exposes three getters. Each returns null if no mounted widget currently uses the key.
| Getter | Returns | Typical use |
|---|---|---|
| `currentWidget` | The `Widget` configuration | Rarely needed |
| `currentContext` | The `BuildContext` (the Element) | `Scrollable.ensureVisible`, size lookups |
| `currentState` | The `State` object, if the widget is stateful | Calling methods such as `validate()` |
The most common use is a Form. The Save button sits next to the form fields, not inside the Form widget, so Form.of(context) would not find the form from that button's context. A GlobalKey<FormState> solves this:
import 'package:flutter/material.dart';
class SignupForm extends StatefulWidget {
const SignupForm({super.key});
@override
State<SignupForm> createState() => _SignupFormState();
}
class _SignupFormState extends State<SignupForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (value) =>
(value == null || value.isEmpty) ? 'Required' : null,
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// All fields are valid.
}
},
child: const Text('Save'),
),
],
),
);
}
}Notice where the key is created: as a final field in the State class, not inside build. The key must live as long as the widget it identifies. This is the single most important rule for GlobalKey, and the Pitfalls section below explains what happens when you break it.
The type argument matters
GlobalKey<FormState> is typed, so currentState returns a FormState? and you can call validate() without a cast. An untyped GlobalKey returns State<StatefulWidget>?, and you would need to cast it yourself. Always supply the type argument for the State you want to reach.
Handling null
currentState is null in three situations:
- The key has not been attached to any widget yet, for example if you read it before the first
build. - The widget was removed from the tree.
- The key is attached to a widget of a different State type than the one in the type argument.
The ! in the example above is acceptable because the button can only be tapped while the form is mounted. In code that may run at other times, such as an async callback after a delay, check for null instead of using !.
Moving a widget between parents
Without a global key, moving a widget to a different parent destroys its State. The old parent's child list no longer contains it, so its Element is unmounted. The new parent builds a fresh Element and a fresh State.
With a GlobalKey, the framework can find the existing Element by looking up the key in its registry. When a widget with that key appears under a new parent in the same frame in which it disappeared from the old one, Flutter reparents the Element instead of recreating it. This process is called inactive-element reuse. Elements that lose their parent during a frame are held in an inactive list until the end of the frame. Any global-keyed widget that is inserted during that frame can claim its old Element back. Elements left unclaimed at the end of the frame are disposed.
Two consequences follow from this:
- The move must happen within one frame. If the widget is absent for a whole frame, its State is disposed.
- The State's
disposeis not called during a successful move.deactivateis called when the Element leaves its old parent, andactivateis called when it joins the new one.
The following example moves one counter between a top area and a bottom area. The counter keeps its count across the move.
import 'package:flutter/material.dart';
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => setState(() => _count++),
child: Text('Taps: $_count'),
);
}
}
class MovingCounter extends StatefulWidget {
const MovingCounter({super.key});
@override
State<MovingCounter> createState() => _MovingCounterState();
}
class _MovingCounterState extends State<MovingCounter> {
final _counterKey = GlobalKey();
bool _onTop = true;
@override
Widget build(BuildContext context) {
final counter = Counter(key: _counterKey);
return Column(
children: [
Container(
height: 60,
color: Colors.blue.shade100,
child: _onTop ? counter : null,
),
Container(
height: 60,
color: Colors.green.shade100,
child: _onTop ? null : counter,
),
ElevatedButton(
onPressed: () => setState(() => _onTop = !_onTop),
child: const Text('Move'),
),
],
);
}
}Place MovingCounter as the body of a Scaffold so TextButton has a Material ancestor. Tap the counter a few times, then press Move. The counter jumps to the other container and keeps its count. If you change Counter(key: _counterKey) to Counter(), the count resets to zero on every move.
Here is the sequence the framework follows during the frame in which _onTop changes.
Using a GlobalKey for other lookups
Because currentContext gives you the Element, you can reach the RenderObject too. Two common uses:
- Measuring a widget after layout:
(key.currentContext!.findRenderObject() as RenderBox).size. - Scrolling a widget into view:
Scrollable.ensureVisible(key.currentContext!). This only works if the widget is currently built. In a lazyListView.builder, an off-screen item has no Element, socurrentContextisnull.
Reading these values inside build is wrong, because layout has not happened yet in that frame. Read them in a callback, or schedule the read with WidgetsBinding.instance.addPostFrameCallback.
Pitfalls
Duplicate GlobalKeys
If the same GlobalKey instance is used by two widgets that are both in the tree at the end of a frame, Flutter throws an error such as "Multiple widgets used the same GlobalKey". A frequent cause is building the same widget instance into two places at once, for example showing a tablet layout and a phone layout in the same frame and keying a child in both. Make sure only one branch builds the keyed widget at any time.
Creating the key inside build
This code is a bug:
@override
Widget build(BuildContext context) {
return Form(
key: GlobalKey<FormState>(), // New key on every build.
child: const SizedBox(),
);
}Each rebuild creates a different key. The matching rule sees a different key, so it discards the old Element and State and builds new ones. The form loses its field values on every setState. Create the key once, in a State field or initState.
Cost
GlobalKey registration and lookup is more expensive than comparing local keys, and the framework must do extra work to handle reparenting. A few dozen keys are fine. Keying every item of a long list with a GlobalKey is a mistake: use ValueKey or ObjectKey for identity within a list, and reserve GlobalKey for the cases that need cross-parent access.
Overuse as a communication channel
Reaching into another widget's State with currentState couples two parts of the UI tightly. It works for framework-defined cases such as FormState, ScaffoldState or NavigatorState. For your own widgets, prefer passing a callback down or lifting the state up, which the last chapter of this tutorial compares in detail.
Summary of when to use it
| Need | Use GlobalKey? |
|---|---|
| Keep state when reordering items in one list | No, use `ValueKey` or `ObjectKey` |
| Call `validate()` or `save()` on a form from a button outside it | Yes |
| Move a stateful subtree between two parents without losing state | Yes |
| Measure or scroll to a specific built widget | Yes |
| Let a parent read a child's counter | Usually no, lift state up |
Exercise
A screen shows a stateful video player widget inside a Column in portrait mode and inside a Row in landscape mode. Rotating the device restarts the video. Which key fixes this, where should it be created, and why must the swap happen in a single frame?
Show answer
Give the player widget a GlobalKey, for example final _playerKey = GlobalKey(); as a field in the State of the widget that builds the Column or Row, and pass VideoPlayer(key: _playerKey) in both branches. The Column and Row are different parent widgets, so a local key would not match across them. The GlobalKey lets the framework find the player's inactive Element in its registry and reattach it. This only works if the new branch builds the keyed widget in the same frame in which the old branch stops building it, because inactive Elements that nobody claims by the end of the frame are disposed. The key must not be created inside build, or each rebuild would produce a new key and reset the player.
Exercise
Why is currentState possibly null when you call _formKey.currentState!.validate() from a timer callback that fires after the user left the screen?
Show answer
After the screen is popped, the Form's Element is unmounted and removed from the GlobalKey registry, so currentState returns null and the ! operator throws. Check for null (for example _formKey.currentState?.validate()), or cancel the timer in dispose.