Sub topic 13
Choosing between keys, keep-alive and lifting state up
This chapter assumes you know the Widget, Element and State relationship, the matching rule (same runtimeType and same key means the Element and its State are reused), and the key types from the earlier chapters: ValueKey, ObjectKey, UniqueKey, PageStorageKey and GlobalKey. You should also be comfortable with setState, ListView and TabBarView.
You now have three ways to stop state from disappearing or landing in the wrong place. They solve different problems, so picking one starts with diagnosing why the state was lost.
Diagnose first: why did the state change?
When state looks wrong, it is usually one of three situations.
- The State is attached to the wrong widget. The Element was reused, but it was matched to a different item than you intended. This is the reorder problem. The fix is a key.
- The State was destroyed. The Element was removed from the tree, so its State was disposed. This happens when a lazy parent such as
ListView.builderscrolls an item off screen, whenTabBarViewleaves a tab, or when a route is popped. The fix is to keep the Element alive, or to store the value somewhere that outlives it. - The State lives in the wrong place. Another widget needs the value, or the value must survive the widget's removal. The fix is to move the state up to an ancestor or into a model.
The diagram turns these questions into a decision path.
When keys are the right tool
Use a key when the Element survives but the matching is ambiguous. The signal is a collection of stateful widgets whose order, count or contents change at runtime: reorderable lists, lists with insertions or removals, and swapped siblings.
- Use
ValueKeywhen each item has a stable, unique value such as an id or a label. - Use
ObjectKeywhen identity comes from a combination of fields, or from the model object itself. - Place the key on the topmost widget returned for each item. If you wrap an item in a
Paddingand put the key on the inner widget, thePaddingis what sits in the list, and it has no key.
Keys do not keep a widget alive. A keyed item that scrolls out of a ListView.builder is still disposed. A key only decides which existing Element a new widget is matched with.
Two key types sit at the edge between categories:
PageStorageKeysaves a small value, usually a scroll offset, in the nearestPageStorage. The widget is still rebuilt from scratch, but it restores that value. Use it when scroll position is all you need to keep.GlobalKeygives you access to a State from anywhere, and lets a widget move to a different parent without losing its State. Use it when you need that reach or move. Do not use it only to keep state alive.
When keep-alive is the right tool
Use AutomaticKeepAliveClientMixin when a widget's own State must survive being scrolled or swiped out of view, and the State is local to that widget. Typical cases are a tab holding a half-filled form, a video player position, or a search field with typed text.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: TabsDemo()));
class TabsDemo extends StatelessWidget {
const TabsDemo({super.key});
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [Tab(text: 'One'), Tab(text: 'Two')],
),
),
body: const TabBarView(children: [MyTab(), MyTab()]),
),
);
}
}
class MyTab extends StatefulWidget {
const MyTab({super.key});
@override
State<MyTab> createState() => _MyTabState();
}
class _MyTabState extends State<MyTab> with AutomaticKeepAliveClientMixin {
int _count = 0;
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context); // Required by the mixin.
return Center(
child: TextButton(
onPressed: () => setState(() => _count++),
child: Text('Taps: $_count'),
),
);
}
}Tap the counter on the first tab, switch to the second tab and back. The count is still there. Remove the mixin and the count resets to zero, because TabBarView builds its pages lazily and disposes the one you left.
Keep these limits in mind:
- The mixin only works under a parent that understands keep-alive notifications, such as
ListView,GridVieworTabBarView. In a plainColumnthere is nothing to ask, and nothing needs asking, because aColumnnever disposes its children. - You must call
super.build(context)insidebuild. Forgetting it silently disables keep-alive. - Kept-alive widgets stay in memory. Applying it to every row of a 10,000-item list defeats the purpose of
ListView.builder. Reserve it for a few widgets whose state is expensive or impossible to rebuild. wantKeepAlivecan change over time. If it does, callupdateKeepAlive()so the parent re-reads it.- Keep-alive keeps the widget's State only while the app runs and the parent exists. If the parent is removed, or the user pops the route, the State goes with it.
When lifting state up is the right tool
Lift state up when the value is really data, not UI detail. Move it into a common ancestor, or into a model object that the ancestor owns, and pass it down to stateless children. This is often the best fix, because it removes the cause of the problem instead of working around it.
Lift state up when any of these apply:
- Another widget needs to read or change the value, such as a badge counting checked items.
- The value must survive the widget being disposed, with no keep-alive trick.
- You want the value to be testable without pumping widgets.
- You keep adding keys to protect state that nothing in the UI truly owns.
Here is the reorder problem solved without keys. The done flag lives in a Task model owned by the list's State, and TaskTile is stateless.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: Scaffold(body: TaskList())));
}
class Task {
Task(this.title);
final String title;
bool done = false;
}
class TaskList extends StatefulWidget {
const TaskList({super.key});
@override
State<TaskList> createState() => _TaskListState();
}
class _TaskListState extends State<TaskList> {
List<Task> _tasks = [Task('Write'), Task('Test'), Task('Ship')];
void _reverse() {
setState(() => _tasks = _tasks.reversed.toList());
}
@override
Widget build(BuildContext context) {
return Column(
children: [
for (final task in _tasks)
TaskTile(
task: task,
onChanged: (value) => setState(() => task.done = value),
),
TextButton(onPressed: _reverse, child: const Text('Reverse')),
],
);
}
}
class TaskTile extends StatelessWidget {
const TaskTile({super.key, required this.task, required this.onChanged});
final Task task;
final ValueChanged<bool> onChanged;
@override
Widget build(BuildContext context) {
return CheckboxListTile(
title: Text(task.title),
value: task.done,
onChanged: (value) => onChanged(value ?? false),
);
}
}Check a task, then press Reverse. The checkmark follows its title. Nothing positional is stored in an Element, so the matching rule has nothing to get wrong.
Lifting up has limits too:
- If the children still contain hidden State, such as a
TextFieldwith a controller, anAnimationControlleror focus, those pieces still need keys when the list reorders. - The owner must live long enough. State lifted into a widget that is itself disposed is lost. For state that must outlive a route or the whole screen, place the model higher, or in a state management solution.
- Lifting up does not survive an app restart. That needs persistence or Flutter's restoration APIs, which are outside this chapter.
Comparing the options
| Approach | Solves | Cost | Does not solve |
|---|---|---|---|
| `ValueKey` or `ObjectKey` | State attached to the wrong item after reorder, insert or remove | Almost none; requires a stable identity | Disposal of off-screen items |
| `PageStorageKey` | Lost scroll position across tab or route changes | Small; needs a `PageStorage` ancestor | Other State, such as text input |
| `GlobalKey` | Reaching a State from outside; moving a widget between parents | Registry bookkeeping; must be unique in the whole tree | Persistence after the widget is removed |
| `AutomaticKeepAliveClientMixin` | Local State lost when a lazy parent disposes the widget | Memory for every kept widget | Wrong matching on reorder |
| Lifting state up | Shared data, data that must outlive widgets, reorder with stateless children | More wiring between widgets | Hidden State in children, app restarts |
Worked scenarios
- A to-do list where users drag rows to reorder them. Each row is a stateful widget with a text field. Use
ValueKey(todo.id)on the row. If a row's checked flag is also shown in a summary bar, lift that flag into the model as well. - A feed in a
TabBarView, where users complain the feed jumps to the top when they return to the tab. The State was disposed, and only the scroll offset matters. Add aPageStorageKeyto theListView. If the tab also holds a draft comment, add keep-alive to that tab's State. - A settings form with a Save button in the app bar. The button sits outside the
Formsubtree. Create aGlobalKey<FormState>once in State and callvalidate(). If you only needed to know whether the fields are filled, passing values up through callbacks would avoid the global registry. - A shopping cart with a badge on the app bar. The badge and the product rows both need the quantity. Lift it into a model. A key or keep-alive would not help, because the problem is ownership.
Common mistakes when choosing
- Using
UniqueKeyto "fix" a reset or a reorder. It creates a new identity on every build, so every build discards the State. It is correct only when you want that reset. - Reaching for
GlobalKeyfirst. It works for many problems, but it creates tight coupling and a cost in a global registry. Try a callback or a lifted model first. - Adding keep-alive to everything to stop flicker. Find out what state is expensive to rebuild, and keep only that.
- Assuming a key preserves state across a lazy parent's disposal. It does not.
Exercise
A ListView.builder shows 500 rows. Each row is a stateful widget with a "favorite" toggle in its own State. Users report that scrolling a row away and back resets its toggle. Which approach fits, and why is a key not enough?
Show answer
Lift the favorite flag into a model, for example a Set<int> of favorite ids owned above the list, and make the row read from it. A key does not help because the row's Element is disposed when it scrolls off screen, so no matching happens when it returns. Keep-alive on all 500 rows would work but keeps every row in memory, which defeats ListView.builder.
Exercise
You use TabBarView with three tabs. Tab two has a TextField whose typed text vanishes when the user switches tabs. Name the two changes you need in the tab's State class.
Show answer
Mix in AutomaticKeepAliveClientMixin and override wantKeepAlive to return true, and call super.build(context) at the start of build. The TextField's controller lives in this State, so keeping the State alive keeps the text.
Exercise
A teammate puts UniqueKey() on each row in the build method of a reorderable list, to "make sure rows never get mixed up". What happens, and what should they use instead?
Show answer
Every rebuild creates new keys, so no new widget matches any old Element. All rows are disposed and recreated, and every row loses its State, so the list is not mixed up but is fully reset. They should use ValueKey with a stable id from the item, or ObjectKey with the model object.