Sub topic 11
AutomaticKeepAliveClientMixin for lazy lists and tabs
This chapter assumes you know how Flutter matches widgets to Elements by runtimeType and key. It also assumes you know that a State object lives on its Element, and that you can build a TabBar or ListView.builder screen. Keys decide which State an Element keeps while it stays in the tree. This chapter covers a different problem: a lazy parent removes the Element from the tree, and the State is lost.
Why state disappears in lazy containers
Some widgets build only the children that are visible or nearby:
ListView.builderandGridView.builderbuild items on demand and dispose items that scroll far off screen.TabBarViewandPageViewbuild the current page and its neighbors. Pages that move away are disposed.
When an Element is disposed, its State goes with it. dispose() runs, and the next time the child is needed Flutter creates a fresh State, so _count is back to 0.
A key cannot fix this. Keys only affect matching between a new widget and an Element that is still in the tree. Here no Element is left to match. You need a way to tell the parent: "Do not dispose me, even though I am off screen."
How keep-alive works
AutomaticKeepAliveClientMixin is that mechanism. The pieces are:
- The lazy parent wraps each child in an
AutomaticKeepAlivewidget. This is on by default through theaddAutomaticKeepAlives: trueparameter of lists, grids and pages. - Your State mixes in
AutomaticKeepAliveClientMixin. WhenwantKeepAliveistrue, the mixin sends aKeepAliveNotificationup the tree. - The parent receives it and moves the child's Element into a keep-alive bucket instead of disposing it. The child is not painted or laid out while it is off screen, but its Element and State stay in memory.
- When the child scrolls back, Flutter reuses the same Element and State.
Using the mixin
The mixin has three requirements:
- Mix it into the
Stateclass, not the widget. - Override the
wantKeepAlivegetter to returntrue. - Call
super.build(context)at the start ofbuild. This is how the mixin registers the keep-alive request.
Here is a complete app with a TabBarView. Each tab keeps its counter when you switch away.
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: 3,
child: Scaffold(
appBar: AppBar(
title: const Text('Keep-alive tabs'),
bottom: const TabBar(
tabs: [Tab(text: 'One'), Tab(text: 'Two'), Tab(text: 'Three')],
),
),
body: const TabBarView(
children: [MyTab(), 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, move to the third tab, then return. The count is still there. Remove the mixin and the count resets to 0 whenever the tab is rebuilt. The first tab is disposed once you are two tabs away, so switch to the third tab to see the reset.
Keep-alive in a lazy list
The same mixin works for list items. This is useful when each item holds expensive or hard-to-recreate state, such as a loaded image, a video controller, or text the user typed.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: NoteList())));
class NoteList extends StatelessWidget {
const NoteList({super.key});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: 100,
itemBuilder: (context, index) => NoteField(
key: ValueKey(index),
index: index,
),
);
}
}
class NoteField extends StatefulWidget {
const NoteField({super.key, required this.index});
final int index;
@override
State<NoteField> createState() => _NoteFieldState();
}
class _NoteFieldState extends State<NoteField>
with AutomaticKeepAliveClientMixin {
final _controller = TextEditingController();
@override
bool get wantKeepAlive => true;
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
super.build(context);
return Padding(
padding: const EdgeInsets.all(8),
child: TextField(
controller: _controller,
decoration: InputDecoration(labelText: 'Note ${widget.index}'),
),
);
}
}Type into Note 0, scroll down 30 rows, and scroll back. The text is still there. This example uses both tools: the ValueKey keeps State attached to the right item if the data is reordered, and keep-alive stops the State from being disposed while off screen. They solve different problems and do not replace each other.
Changing the decision at runtime
wantKeepAlive is read when the mixin builds, but it can change over time. If you flip its value, call updateKeepAlive() so the parent re-reads it.
class _PinnableState extends State<Pinnable>
with AutomaticKeepAliveClientMixin {
bool _pinned = false;
@override
bool get wantKeepAlive => _pinned;
void _togglePin() {
setState(() => _pinned = !_pinned);
updateKeepAlive();
}
@override
Widget build(BuildContext context) {
super.build(context);
return SwitchListTile(
title: const Text('Keep me alive'),
value: _pinned,
onChanged: (_) => _togglePin(),
);
}
}
class Pinnable extends StatefulWidget {
const Pinnable({super.key});
@override
State<Pinnable> createState() => _PinnableState();
}This lets you keep only the items that need it, such as ones with unsaved edits, and release the rest.
Limits and gotchas
- The parent must support it. Keep-alive works inside
ListView,GridView,SliverList,SliverGrid,PageViewandTabBarView. It does nothing in aColumnor in a plainStack. Those never dispose their children anyway. addAutomaticKeepAlives: falseturns it off. If you set it on a list, the mixin has noAutomaticKeepAlivewrapper to talk to.- It costs memory. Every kept Element, State and its render objects stay in memory. Keeping all 10,000 items of a long list alive defeats the point of a lazy list. Keep only what is expensive to rebuild.
- The cache extent is not keep-alive. Items inside
cacheExtent(250 logical pixels by default) are built ahead of time and are not disposed yet. They look as if state is being preserved, but they are disposed once they leave that zone. - It does not survive removal from the tree. If the data item is deleted, or the whole route is popped, the State is disposed. Keep-alive only protects against the lazy parent's off-screen disposal.
- It does not survive app restarts. For that you need persistence or
RestorationMixin.
Choosing a strategy
| Situation | Best tool |
|---|---|
| Reordering items in a list or column | `ValueKey` or `ObjectKey` on each item |
| Remember scroll offset when a list is removed and rebuilt | `PageStorageKey` |
| Tab or list item must keep its State while off screen | `AutomaticKeepAliveClientMixin` |
| State must survive an item or route being removed | Lift state up into a parent or a state-management layer |
| Parent needs to call a method on a child's State | `GlobalKey` |
Lifting state up is often the cleanest answer for data such as a counter or a typed value. The data lives above the lazy boundary, so the widget can be disposed and rebuilt at no cost. Use keep-alive when the state is tied to the widget itself, such as a controller, an animation, a scroll position inside a nested scrollable, or a loaded video.
Exercise
A TabBarView has three tabs. Each tab is a StatefulWidget with a counter. Users report that the counter on tab 1 resets after they visit tab 3. You add ValueKey('tab1') to the first tab, but the counter still resets. Why, and what is the fix?
Show answer
A key only helps match a new widget to an Element that is still in the tree. TabBarView disposes tab 1's Element when it is two pages away, so there is nothing left to match and the State is lost. Fix it by mixing AutomaticKeepAliveClientMixin into the tab's State, returning true from wantKeepAlive, and calling super.build(context) in build. Alternatively, lift the counter into a parent above the TabBarView.
Exercise
You mix AutomaticKeepAliveClientMixin into a list item's State and return true from wantKeepAlive, but the item's text field still loses its text when scrolled away. You have checked the mixin and the getter. What is the most likely missing line?
Show answer
The call super.build(context) at the start of the State's build method. Without it the mixin never sends its keep-alive notification, so the parent disposes the item as usual.