GlobalKey is a special type of key in Flutter. It's unique across your entire app. This means you should not create a new GlobalKey every time your widget builds. Instead, think of it as a long-lasting object that belongs to a widget's state.
Using GlobalKeys
Use Case 1: Accessing Widget State
One common use is to get access to the state of a stateful widget from outside that widget. A great example is validating a form. You can attach a GlobalKey to a Form
widget to later get its FormState
and call methods like validate()
.
final GlobalKey<FormState> _formKey = GlobalKey<FormState>(debugLabel: 'form');
// Later, to validate:
bool isFormValid() {
if (_formKey.currentState == null) {
return false;
}
return _formKey.currentState!.validate();
}
Use Case 2: Moving Widgets Without Losing State
GlobalKeys are also super helpful when you need a widget to move to a different spot in the widget tree without losing its current state.
This is often done using KeyedSubtree
. By giving a widget a GlobalKey and wrapping it or its parent in KeyedSubtree
, Flutter can recognize the widget even if its position changes. A classic example where this happens automatically is with Hero
widgets, which smoothly animate between screens while keeping their state.
class _HeroState extends State<Hero> {
final GlobalKey _key = GlobalKey();
Widget build(BuildContext context) {
return SizedBox(
width: _placeholderSize?.width,
height: _placeholderSize?.height,
child: Offstage(
offstage: showPlaceholder,
child: TickerMode(
enabled: !showPlaceholder,
child: KeyedSubtree(key: _key, child: widget.child),
),
),
);
}
}