Sub topic 13
Keys and preserving state
This chapter assumes you can write a StatelessWidget and a StatefulWidget, and that you know how setState and the State lifecycle work. It also assumes you have met the widget, element, and render object split. Here you will learn how Flutter decides whether a State object stays attached to a widget, and how keys change that decision.
The problem keys solve
A State object does not belong to a widget. Widgets are cheap, immutable descriptions that Flutter throws away and recreates on every rebuild. The State lives in an element, which is the long-lived object that sits in the tree at a given position.
When a parent rebuilds, Flutter walks its children and compares each new widget with the widget that the existing element currently holds. If the two can be matched, the element stays and is given the new widget. The State survives, and didUpdateWidget is called. If they cannot be matched, the old element is discarded, its State is disposed, and a new element and a new State are created.
The matching rule is short. Flutter calls Widget.canUpdate, which returns true when both of these hold:
- The two widgets have the same
runtimeType. - The two widgets have equal
keyvalues. Twonullkeys count as equal.
With no keys, the rule reduces to "same type at the same position in the child list". That is enough for most screens. It fails when children of the same type change position, because Flutter then pairs old elements with new widgets by position and not by identity.
A bug you can reproduce
Take a list of tiles where each tile keeps its own state, here a checkbox. The list can be reversed.
import 'package:flutter/material.dart';
class Item {
const Item(this.id, this.title);
final int id;
final String title;
}
class CheckTile extends StatefulWidget {
const CheckTile({super.key, required this.item});
final Item item;
@override
State<CheckTile> createState() => _CheckTileState();
}
class _CheckTileState extends State<CheckTile> {
bool _checked = false;
@override
Widget build(BuildContext context) {
return CheckboxListTile(
title: Text(widget.item.title),
value: _checked,
onChanged: (value) => setState(() => _checked = value ?? false),
);
}
}
class BrokenList extends StatefulWidget {
const BrokenList({super.key});
@override
State<BrokenList> createState() => _BrokenListState();
}
class _BrokenListState extends State<BrokenList> {
List<Item> _items = const [
Item(1, 'Milk'),
Item(2, 'Eggs'),
Item(3, 'Bread'),
];
void _reverse() {
setState(() => _items = _items.reversed.toList());
}
@override
Widget build(BuildContext context) {
return Column(
children: [
ElevatedButton(onPressed: _reverse, child: const Text('Reverse')),
for (final item in _items) CheckTile(item: item),
],
);
}
}Check "Milk" and press Reverse. The titles reverse, but the checkmark stays in the first row, which is now "Bread". The checked state belongs to the first element, and that element was reused for whatever widget came first.
The following diagram shows what Flutter does at each position.
Fixing it with ValueKey
Give each tile a key derived from a stable identity. Flutter then matches elements by key first, so the element that held "Milk" follows "Milk" to its new position.
@override
Widget build(BuildContext context) {
return Column(
children: [
ElevatedButton(onPressed: _reverse, child: const Text('Reverse')),
for (final item in _items)
CheckTile(key: ValueKey(item.id), item: item),
],
);
}Only the build method of _BrokenListState changes. The same idea applies to ListView children, as in the Topic Spine example:
class TodoList extends StatelessWidget {
const TodoList({super.key, required this.todos});
final List<Todo> todos;
@override
Widget build(BuildContext context) {
return ListView(
children: [
for (final todo in todos)
TodoTile(key: ValueKey(todo.id), todo: todo),
],
);
}
}This snippet assumes a Todo class with an id field and a stateful TodoTile widget that accepts key and todo.
Choosing a key type
Flutter provides several key classes. They differ in how equality is defined and in how far the key's scope reaches.
| Key | Equal when | Typical use |
|---|---|---|
| `ValueKey<T>` | the wrapped values are equal (`==`) | list items with a stable id or unique string |
| `ObjectKey` | the wrapped objects are identical | items identified by object instance, with no simple id |
| `UniqueKey` | never equal to any other key | force a fresh State on every build |
| `GlobalKey` | the same key instance is used | reach a State from elsewhere, or move a subtree between parents |
| `PageStorageKey` | the wrapped values are equal | remember scroll position in scrollables |
Keys other than GlobalKey are local keys. They only need to be unique among siblings, not across the whole app.
Choosing the value for a ValueKey
A ValueKey is only as good as its value. Use a value that stays the same for the same logical item and differs between items.
- Use a database id, a UUID, or a unique name.
- Do not use the list index. After a reorder, the index identifies the position, which is exactly what you are trying to stop relying on.
- Do not use a value that can repeat. Two siblings with equal keys cause an assertion error in debug mode ("Duplicate keys found").
- Do not use a value that changes when the item is edited, such as the title. The State would be thrown away on every edit.
Using a key to reset state
Keys also work in the other direction. If you want a State to be discarded, change the key. The old element no longer matches, so Flutter builds a new one.
A typical case is a form that edits one user at a time. When the selected user changes, you want the text field's controller to start over with the new initial value.
import 'package:flutter/material.dart';
class User {
const User(this.id, this.name);
final int id;
final String name;
}
class NameField extends StatefulWidget {
const NameField({super.key, required this.initialName});
final String initialName;
@override
State<NameField> createState() => _NameFieldState();
}
class _NameFieldState extends State<NameField> {
late final TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: widget.initialName);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(controller: _controller);
}
}
class UserEditor extends StatelessWidget {
const UserEditor({super.key, required this.user});
final User user;
@override
Widget build(BuildContext context) {
return NameField(
key: ValueKey(user.id),
initialName: user.name,
);
}
}initState reads initialName only once. Without the key, switching from one User to another keeps the same State, and the field still shows the old text. With ValueKey(user.id), a new user produces a new State, so initState runs again with the new name. The other fix is to handle the change in didUpdateWidget, which suits cases where you want to keep other parts of the State.
Swapping widgets of different types
Keys are not needed when the type changes. If a parent switches between a Text and an Icon in the same slot, canUpdate returns false because the runtimeType differs, and the element is replaced.
A subtle case is a conditional wrapper of the same type. Consider two Counter widgets in a Column where one is shown only some of the time:
Column(
children: [
if (showFirst) const Text('First'),
const Counter(),
],
)In a collection if, Flutter keeps the slot for the missing item, so the Counter keeps its position and its State. Problems appear when two same-typed widgets swap places in different branches of a conditional. Give them distinct keys in that situation.
GlobalKey: power and cost
A GlobalKey is unique across the whole app. It has two uses.
- Access the State from outside.
globalKey.currentStatereturns theStateobject, so you can call its methods.FormStateandScaffoldStateare commonly reached this way. - Move a subtree to a different parent while keeping its State. Flutter can reparent the element within the same frame.
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()) {
// Submit the form.
}
},
child: const Text('Submit'),
),
],
),
);
}
}Create a GlobalKey once and store it in a State field, as above. If you create it inside build, every rebuild produces a new key, and the State is lost each time.
A GlobalKey must also be unique in the tree at any moment. Two widgets with the same GlobalKey in the same frame throw an error.
Preserving scroll position with PageStorageKey
Scrollable widgets store their scroll offset in a PageStorage bucket. When a scrollable is removed and later rebuilt, for example when you switch tabs, a PageStorageKey lets it find its saved offset again.
ListView.builder(
key: const PageStorageKey<String>('inbox-list'),
itemCount: 100,
itemBuilder: (context, index) => ListTile(title: Text('Message $index')),
)Each scrollable that should remember its position needs a different key value. Without PageStorageKey, a scrollable that gets disposed starts again at the top.
Rules of thumb
- Add keys when children of the same type can be reordered, inserted, or removed and each holds State.
- Skip keys for fully stateless children whose position does not matter. The result looks the same, and keys add noise.
- Choose keys from data identity, never from position.
- Change a key on purpose to reset a State.
- Reach for
GlobalKeylast.
Exercise
A ListView shows Note items, each in a stateful NoteTile that stores whether the note is expanded. Users can delete a note from the middle of the list. After a deletion, the wrong tile appears expanded. The code builds tiles with NoteTile(note: note). Name the cause and give the fix, including which value to use for the key and which value to avoid.
Show answer
Without keys, Flutter matches elements to widgets by type and position. After a deletion, the element that held the removed note's expanded State is reused for the next note in the list. The fix is NoteTile(key: ValueKey(note.id), note: note), using a stable unique id. Avoid the list index, because it describes the position and changes after a deletion. Avoid the note's text or title as well if it can repeat or change.
Exercise
A UserEditor shows a NameField whose controller is created in initState from widget.initialName. When the parent passes a different user, the text field keeps showing the previous name. Give two ways to fix it.
Show answer
First, give the field a key tied to the user, such as ValueKey(user.id), so a new user creates a new State and initState runs again. Second, override didUpdateWidget in the State, compare oldWidget.initialName with widget.initialName, and update the controller's text when they differ.