Sub topic 14
Keys and Preserving State of List Items
This chapter explains why a list item can lose its state or show another item's state. It also covers how to prevent both problems. It assumes you can write StatefulWidget classes and use ListView.builder as covered in earlier chapters. Knowing that Flutter has a widget tree and an element tree helps, but the chapter explains what you need.
Why list item state is fragile
Two things can go wrong with stateful list items.
- The state disappears when the item scrolls away.
ListView.buildercreates items lazily and disposes the ones that leave the viewport (plus a small cache area). When you scroll back, Flutter creates a newStateobject with fresh values. A checkbox, a text field's contents, or an expanded panel resets. - The state attaches to the wrong item. When the list changes (an item is removed, inserted, or reordered), Flutter has to decide which existing
Statebelongs to which new widget. Without help, it can pair the wrong ones.
Keys and keep-alive mechanisms address these problems. They are different tools, so first identify which problem you have.
How Flutter matches widgets to state
Widgets are cheap, immutable descriptions. The framework keeps a longer-lived element for each widget, and a StatefulElement holds the State object. When a parent rebuilds, Flutter compares the new widget at each position with the old element at that position. If the runtimeType and key match, it reuses the element and its State. Otherwise it discards them and creates new ones.
If you give no key, key is null for all items. Items of the same type then match by position only. If you remove the first row, the old second row's element is paired with the new first widget, and so on. The data moves, but the State stays at its position.
Reproducing the bug
This app shows four names. Each row is a stateful widget holding its own checkbox value. Check "Ada", then press Remove first. Without a key, "Grace" becomes the first row and appears checked, because the first element kept its State.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: KeyDemo())));
class KeyDemo extends StatefulWidget {
const KeyDemo({super.key});
@override
State<KeyDemo> createState() => _KeyDemoState();
}
class _KeyDemoState extends State<KeyDemo> {
final List<String> _names = ['Ada', 'Grace', 'Linus', 'Margaret'];
void _removeFirst() {
if (_names.isEmpty) return;
setState(() => _names.removeAt(0));
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TextButton(
onPressed: _removeFirst,
child: const Text('Remove first'),
),
Expanded(
child: ListView.builder(
itemCount: _names.length,
itemBuilder: (context, index) {
final name = _names[index];
// Remove the key argument to see the bug.
return CheckTile(key: ValueKey(name), name: name);
},
),
),
],
);
}
}
class CheckTile extends StatefulWidget {
const CheckTile({super.key, required this.name});
final String name;
@override
State<CheckTile> createState() => _CheckTileState();
}
class _CheckTileState extends State<CheckTile> {
bool _checked = false;
@override
Widget build(BuildContext context) {
return CheckboxListTile(
title: Text(widget.name),
value: _checked,
onChanged: (value) => setState(() => _checked = value ?? false),
);
}
}With ValueKey(name), each element is matched by identity. When "Ada" is removed, her element is discarded and "Grace" keeps her own unchecked State.
Choosing a key type
| Key | Equality | Use it when |
|---|---|---|
| `ValueKey<T>` | Same value (`==`) | Each item has a stable unique value such as an id or a unique name |
| `ObjectKey` | Same object instance (`identical`) | The item is a model object with no single unique field |
| `UniqueKey` | Never equal to any other key | You deliberately want a fresh state each time |
| `GlobalKey` | Unique across the whole app | You must reach an item's `State` or move it between parents |
| `PageStorageKey` | Value-based, also used as a storage id | You want a scrollable to remember its scroll offset |
Several rules apply to all of them.
- Keys must be unique among siblings. Two items with the same
ValueKeyin one list throw a duplicate key error. - Use a stable identity, not the index.
ValueKey(index)behaves like no key, because the index describes the position, which is exactly what changes. - Put the key on the top widget the builder returns. If you wrap the stateful widget in
Paddingand key only the inner widget, the outer widget still matches by position.
GlobalKey is the heaviest option. The framework tracks it in a global registry, and overuse slows rebuilds. Prefer ValueKey for lists.
Helping the builder find moved items
When a list reorders, ListView.builder has to find where each keyed item went. By default it may scan, which is slow for long lists. The optional findChildIndexCallback maps a key to its new index.
ListView.builder(
itemCount: _names.length,
findChildIndexCallback: (Key key) {
final name = (key as ValueKey<String>).value;
final index = _names.indexOf(name);
return index == -1 ? null : index;
},
itemBuilder: (context, index) {
final name = _names[index];
return CheckTile(key: ValueKey(name), name: name);
},
)Return null when the key is no longer in the list. This callback matters mostly for large, frequently reordered lists. For short lists you can skip it.
Keeping state while items are off-screen
Keys fix mismatched state. They do not stop an item from being disposed when it scrolls out of view. For that, the item's State can mix in AutomaticKeepAliveClientMixin.
import 'package:flutter/material.dart';
class CounterTile extends StatefulWidget {
const CounterTile({super.key, required this.index});
final int index;
@override
State<CounterTile> createState() => _CounterTileState();
}
class _CounterTileState extends State<CounterTile>
with AutomaticKeepAliveClientMixin {
int _count = 0;
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context); // required by the mixin
return ListTile(
title: Text('Row ${widget.index}: $_count'),
trailing: IconButton(
icon: const Icon(Icons.add),
onPressed: () => setState(() => _count++),
),
);
}
}Use it in a builder list:
ListView.builder(
itemCount: 200,
itemBuilder: (context, index) => CounterTile(index: index),
)Increment row 0, scroll far away, and scroll back. The count survives. Three details matter.
- Call
super.build(context)at the start ofbuild. Without it, the keep-alive request is never registered. wantKeepAlivecan change over time. If it does, callupdateKeepAlive()so the framework re-reads it. A common pattern is to returntrueonly while the user has typed something.- Kept items stay in memory, and their widgets keep running animations and listeners. Keeping all items alive in a 10,000-row list defeats lazy building.
Lifting state up as the usual answer
Keep-alive is a patch. The more robust fix is to store item state in your data, not in the widget. Instead of a bool _checked inside each tile, keep a Set<String> of checked ids in the parent (or in a state-management object), and make the tile stateless. The tile then rebuilds correctly from the data whenever it is created. This approach has three advantages.
- Memory use stays low, because disposed items hold no state.
- The state survives app features that rebuild the whole list, such as filtering and sorting.
- You can save or send the state, for example to a server.
Reserve AutomaticKeepAliveClientMixin for state that is awkward to lift, such as a video controller or a half-typed text field in a few items.
Remembering scroll position with PageStorageKey
Scroll position is another piece of state. A ListView inside a TabBarView is disposed when you switch tabs, and it comes back at the top. A PageStorageKey makes the scrollable save its offset into the nearest PageStorage bucket, which Scaffold and Navigator routes provide by default.
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 its own distinct key value. Two lists sharing one key overwrite each other's saved offset. This key stores the offset only. It does not preserve the state of the items themselves.
Common mistakes
- Using the index as a key. It changes meaning when the list changes, so it fixes nothing.
- Keying the wrong widget. The key must sit on the widget the builder returns, not on a descendant.
- Forgetting
super.build(context). Keep-alive silently does nothing. - Keeping everything alive. Memory grows with the number of items visited.
- Expecting keys to prevent disposal. Keys decide matching. They do not keep off-screen items alive.
Exercise
A list of 500 chat messages uses ListView.builder. Each message is a StatefulWidget with a bool _expanded field. Users report that after they scroll down and back up, expanded messages have collapsed. Separately, when a new message is inserted at the top, the wrong message appears expanded. Name one fix for each symptom and say which is the better long-term design.
Show answer
The collapse after scrolling happens because off-screen items are disposed, so fix it with AutomaticKeepAliveClientMixin (wantKeepAlive returns true and build calls super.build) or, better, by moving _expanded into the data model, such as a Set of expanded message ids in the parent. The wrong message appearing expanded after an insert happens because items match by position, so fix it by giving each message widget a ValueKey based on its unique message id. The better long-term design is to lift the expanded state into the data, because it keeps memory low across 500 items and survives rebuilds, and the ValueKey still makes the matching reliable.