Sub topic 5
What keys are: LocalKey and GlobalKey
This chapter assumes basic Dart syntax, StatelessWidget and StatefulWidget, setState, and common widgets such as Column, ListView, and ListTile.
A Flutter screen is represented by several related trees:
- The Widget tree contains configuration objects. Widgets are usually short-lived and immutable.
- The Element tree connects widgets to the running application. Elements usually remain when Flutter rebuilds.
- The State object belongs to a
StatefulElement. It stores values such as counters, text, and animation progress.
Keys help Flutter decide which existing Element belongs to a newly built Widget. A key is an identifier attached to a widget.
The matching rule
When Flutter rebuilds a parent, it compares each new child with widgets from the previous build. For a widget to update an existing Element, its runtime type and key must match.
For unkeyed children, position is important. The first new child is generally compared with the first old child of the same type, the second with the second, and so on. If the data changes order, state can therefore remain at a position instead of following the item that originally owned it.
A key gives Flutter another part of the identity. Among eligible siblings, Flutter can use the key to find the Element that represents the same logical item.
The Key hierarchy
Key is the base class. Its two important branches are LocalKey and GlobalKey.
| Key type | Identity scope | Typical purpose |
|---|---|---|
| `LocalKey` | Siblings under one parent | Match items in a list |
| `GlobalKey` | The entire widget tree | Reach a State or move a subtree |
LocalKey identifies a widget only among its siblings. It does not provide access to the widget from unrelated parts of the tree. Common LocalKey implementations include:
ValueKey<T>uses an equality value, such as an item ID or label.ObjectKeyuses the identity of an object.UniqueKeycreates a new identity that matches no other key.
GlobalKey has a much wider scope. Only one widget in the active tree should use a particular GlobalKey. Flutter can use it to locate the widget's Element and State, even when the caller is outside that widget's subtree.
A small example
This complete example uses a ValueKey for reorderable logical items and a GlobalKey<FormState> to validate a form.
import 'package:flutter/material.dart';
void main() => runApp(const KeyDemoApp());
class KeyDemoApp extends StatelessWidget {
const KeyDemoApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: KeyDemoPage());
}
}
class KeyDemoPage extends StatefulWidget {
const KeyDemoPage({super.key});
@override
State<KeyDemoPage> createState() => _KeyDemoPageState();
}
class _KeyDemoPageState extends State<KeyDemoPage> {
final _formKey = GlobalKey<FormState>();
var _labels = ['A', 'B', 'C'];
void _reverse() {
setState(() => _labels = _labels.reversed.toList());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Keys')),
body: Column(
children: [
Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.all(16),
child: TextFormField(
validator: (value) =>
value == null || value.isEmpty ? 'Required' : null,
decoration: const InputDecoration(labelText: 'Name'),
),
),
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Valid')),
);
}
},
child: const Text('Validate'),
),
TextButton(onPressed: _reverse, child: const Text('Reverse')),
Expanded(
child: ListView(
children: [
for (final label in _labels)
CounterTile(key: ValueKey(label), label: label),
],
),
),
],
),
);
}
}
class CounterTile extends StatefulWidget {
const CounterTile({super.key, required this.label});
final String label;
@override
State<CounterTile> createState() => _CounterTileState();
}
class _CounterTileState extends State<CounterTile> {
var _count = 0;
@override
Widget build(BuildContext context) {
return ListTile(
title: Text('${widget.label}: $_count'),
onTap: () => setState(() => _count++),
);
}
}ValueKey(label) places each counter's identity on the item. After pressing Reverse, the counter state follows its label. The form key lets the button call validate() on the FormState.
Local versus global identity
Use a LocalKey when the problem is matching sibling items. Use a GlobalKey only when you need a capability that local matching does not provide:
- Access a
Stateobject throughglobalKey.currentState. - Access a widget's context through
globalKey.currentContext. - Move a widget and its subtree to another location while preserving its Element and State.
Global keys have costs. They require broader bookkeeping and make ownership harder to understand. Prefer callbacks, shared state, or a LocalKey when those approaches solve the problem.
Exercise
Which key should you use to match a list row by its database ID, and which key would let a button outside a Form call validate()?
Show answer
Use ValueKey(databaseId) for the row and GlobalKey<FormState> for the Form.