Sub topic 11
AutomaticKeepAliveClientMixin for Lazy Lists and Tabs
Prerequisites
This chapter assumes that you can build StatefulWidget classes, update them with setState, and use ListView, Column, and TabBarView. It also assumes that you understand that a widget describes part of the UI, while its State object stores changing data.
Why lazy widgets discard state
A lazy widget creates only the children that are close to the visible area. A lazy ListView can contain thousands of rows without creating thousands of widget subtrees at once. As a row moves far off screen, Flutter may remove its Element and State to save memory.
When the row becomes visible again, Flutter creates it again. Any state stored inside that row, such as an expanded flag or a text field value, starts over unless you use a state-preservation strategy.
AutomaticKeepAliveClientMixin lets a child ask a lazy parent to keep its state alive while the child is off screen.
The basic pattern
Override wantKeepAlive and return true. In build, call super.build(context) before returning the actual child widget.
import 'package:flutter/material.dart';
class MyTab extends StatefulWidget {
const MyTab({super.key});
@override
State<MyTab> createState() => _MyTabState();
}
class _MyTabState extends State<MyTab>
with AutomaticKeepAliveClientMixin<MyTab> {
int _count = 0;
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return Center(
child: TextButton(
onPressed: () => setState(() => _count++),
child: Text('Taps: $_count'),
),
);
}
}The mixin sends a keep-alive request to a parent that supports automatic keep-alives. The parent then keeps this child’s State instead of disposing it when the child leaves the visible area.
The call to super.build(context) is required. It gives the mixin an opportunity to create or update the keep-alive information. Omitting it can make the request ineffective and may produce an assertion in debug mode.
Keep-alive versus keys
A key helps Flutter match a new widget with an existing Element. It answers, “Is this the same item as before?” Keep-alive answers, “Should this off-screen item remain mounted?”
These mechanisms solve different problems:
| Mechanism | Main purpose | Typical example |
|---|---|---|
| `ValueKey` | Match state with the correct item | Reordering editable rows |
| `PageStorageKey` | Save restorable page data | Remembering scroll offset |
| `AutomaticKeepAliveClientMixin` | Keep a child mounted off screen | Preserving tab state |
| Lifted state | Store data outside disposable children | A list model owning edit values |
A key cannot preserve a State that the parent has already discarded. Likewise, keep-alive does not identify an item after a reorder. Use both when both problems exist.
When to use it
Use the mixin when the state belongs naturally to a screen, tab, or list child and recreating it would lose useful temporary work. Examples include:
- A tab containing a partially completed form.
- A list row containing an expanded panel.
- A search result row with a temporary selection.
- A video or editor view that should pause rather than reset when briefly hidden.
Keep-alive consumes memory because the preserved subtree remains mounted. Do not enable it for every child in a very large list without considering the cost.
If the value must survive navigation, process restarts, or removal from the widget tree, keep it in a model or another durable storage layer instead. Keep-alive only preserves the live widget state while the supporting parent keeps the child in its tree.
Common mistakes
- Forgetting
super.build(context). - Expecting keep-alive to work under a parent that does not support automatic keep-alives.
- Returning
truefor thousands of complex children without measuring memory use. - Using keep-alive to solve an item-identity problem caused by reordering.
- Assuming it saves data after the route or entire parent subtree is removed.
If wantKeepAlive can change during the lifetime of the object, call updateKeepAlive() after changing the condition. This tells the parent to reconsider the request.
Exercise
A tab counter resets whenever the user switches tabs. The tab is a StatefulWidget. What should you check first, and what code change usually fixes it?
Show answer
Make the tab State use AutomaticKeepAliveClientMixin, return true from wantKeepAlive, and call super.build(context). Also verify that the tab is inside a parent such as TabBarView that supports keep-alive requests.