Sub topic 10
GlobalKey: reaching State and moving widgets between parents
Assume you know basic Dart, StatelessWidget, StatefulWidget, setState, and common widgets such as Column, ListView, and ListTile. This chapter focuses on GlobalKey, which is different from the local keys used to identify items in one collection.
A GlobalKey identifies one widget across the entire application’s widget tree. Flutter can use it to find that widget’s Element, preserve its State when it changes parents, or expose its State to code outside the widget’s subtree.
Reaching a State object
A common use is connecting a button to a Form that is lower in the tree. Give the form a GlobalKey<FormState>, then use currentState to call methods on the form.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: SignupPage()));
}
class SignupPage extends StatefulWidget {
const SignupPage({super.key});
@override
State<SignupPage> createState() => _SignupPageState();
}
class _SignupPageState extends State<SignupPage> {
final _formKey = GlobalKey<FormState>();
void _save() {
final form = _formKey.currentState;
if (form != null && form.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Form is valid')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sign up')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || !value.contains('@')) {
return 'Enter a valid email';
}
return null;
},
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _save,
child: const Text('Save'),
),
],
),
),
),
);
}
}Create the key once, usually as a field on the owning State. Do not create it inside build. If you create a new key on every rebuild, Flutter sees a different identity and cannot use the previous form state through that key.
currentState can be null while the widget is not mounted. Check for null when the timing is not guaranteed. Similar properties include currentContext and currentWidget.
Moving a widget between parents
A global key also lets Flutter recognize the same element when a widget moves from one parent to another during an update. For example, a stateful editor can move between two panels without losing its text or selection.
The key must identify only one mounted widget at a time:
flowchart TD
A[Editor with GlobalKey] --> B[Panel A]
A --> C[Panel B]
B --> D[State is preserved]
C --> DThe editor can move from Panel A to Panel B because both locations use the same key. Flutter detaches the existing element and attaches it under the new parent instead of creating a new state object.
Reparenting is not free. Flutter deactivates the moved element and its descendants, then rebuilds parts of the subtree. Inherited dependencies may also be updated. Use this feature for a real ownership change, not as a general replacement for state management.
Costs and common mistakes
Global keys are powerful because they work across subtree boundaries. That power has costs:
| Concern | Result |
|---|---|
| Duplicate mounted key | Flutter throws an error |
| Key created in `build` | Identity changes and state may be lost |
| Many global keys | More bookkeeping and harder-to-follow ownership |
| Frequent reparenting | Extra deactivation and rebuilding work |
Use a global key when a parent genuinely needs a child’s imperative API, such as FormState, or when a widget must move between parents while retaining its state. For ordinary list rows, prefer ValueKey or ObjectKey. For scroll restoration, use PageStorageKey.
When possible, lift the important data into a parent or a state-management object instead. Then both possible parents can render the same data, and the data does not depend on a particular widget location.
Exercise
Why should _formKey be a field on State instead of a local variable in build?
Show answer
A field keeps the same GlobalKey across rebuilds. A new key from each build would change the widget's identity and prevent reliable access to the existing FormState.