Sub topic 13
Choosing Between Keys, Keep-Alive, and Lifting State Up
This chapter assumes basic Dart syntax, StatelessWidget, StatefulWidget, setState, Column, ListView, and ListTile. It also assumes you understand that Flutter may reuse an existing Element and its State when it matches a new widget to an old widget.
Keys, keep-alive, and lifted state solve different problems:
- A key helps Flutter identify the same item when widgets move or rebuild.
- Keep-alive prevents some off-screen state from being discarded.
- Lifting state up stores important data outside a temporary widget.
Choosing the wrong tool can produce lost state, state attached to the wrong item, or unnecessary memory use.
Start with the state you need to preserve
Ask what should happen when the widget changes position, leaves the screen, or gets rebuilt.
If a row moves from position 1 to position 3, but it is still the same item, use a stable local key such as ValueKey(item.id). The key tells Flutter that the row's existing state belongs to that item.
If a tab or lazy-list child temporarily leaves the screen and should keep its in-memory state, use a keep-alive mechanism. The widget remains available instead of being disposed.
If the data must survive for a long time, or several widgets need to read and change it, lift the state to a parent or another state-management layer. The data then does not depend on one widget's State object.
Compare the preservation strategies
| Strategy | Preserves | Best use | Main cost |
|---|---|---|---|
| `ValueKey` or `ObjectKey` | State during sibling matching and reordering | Dynamic collections | Requires stable, unique identity |
| `PageStorageKey` | Small saved values such as scroll offset | Returning to a route or tab | It is storage, not a live State object |
| `AutomaticKeepAliveClientMixin` | A child State while it is off screen | Tabs and lazy lists | More children remain in memory |
| Lifted state | Data beyond a widget's lifetime | Forms, drafts, selections, domain data | More explicit state ownership |
| `GlobalKey` | Access to State or moving an element | Form validation or rare subtree moves | Global bookkeeping and tighter coupling |
Use keys for item identity
Suppose a list displays editable rows. Reordering the list should move each row's text field and focus state with its item. Give the topmost widget representing each item a stable key:
CounterTile(
key: ValueKey(item.id),
label: item.label,
)The value must remain stable while the item remains the same. Do not use the list index if items can be inserted, removed, or reordered. An index describes a position, not an item.
Use ObjectKey(item) when object identity is the identity you need. Use ValueKey when a stable value, such as a database ID, identifies the item. Use UniqueKey only when every new widget should be treated as a new item. A UniqueKey created during every build call forces state to reset, so it is usually the wrong choice for ordinary list rows.
Place the key on the item widget that owns the state, or on the topmost widget for that item in the collection. A key on a descendant does not help Flutter match the item's parent element.
Use keep-alive for temporary absence
A lazy list may dispose children that are far outside the viewport. A tab view may also remove or deactivate inactive content depending on its structure. AutomaticKeepAliveClientMixin lets a stateful child request that its state remain alive:
class EditorTabState extends State<EditorTab>
with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return const Text('Editor');
}
}Keep-alive is appropriate for temporary UI state, such as a partially filled tab or a scroll position inside a complex child. It is not a replacement for saving important data. If the application must recover a draft after the page is closed, store the draft in a parent model, repository, or other durable state holder.
Lift state when the data outlives the widget
Lift state up when the state belongs to the screen or feature rather than to one row. For example, a shopping cart should not disappear because its product list was rebuilt. A parent can store quantities by product ID and pass each quantity and callback to the row.
This approach also works when multiple widgets need the same value. It makes ownership clear and avoids depending on element reuse. The trade-off is that more values and callbacks travel through the widget tree, or you introduce a state-management solution.
Choose deliberately
Use this sequence:
- If the same item moves among siblings, add a stable local key.
- If a child is only temporarily off screen, consider keep-alive.
- If the data must survive widget replacement or be shared, lift it up.
- Use
PageStorageKeywhen a framework-supported value, such as scroll offset, should be restored. - Use
GlobalKeyonly when you need cross-subtree access or a genuine global identity.
Exercise
A reorderable list shows stateful rows. The rows must keep their internal state when reordered, but that state does not need to survive leaving the page. Which strategy should you start with?
Show answer
Put a stable ValueKey, usually based on the row's ID, on each row's topmost state-owning widget. Keep-alive is unnecessary unless the rows are also discarded while off screen.