Sub topic 14
Keys and Preserving State of List Items
This chapter assumes basic Dart lists and closures, Flutter widget and state basics, and familiarity with ListView.builder, Column, and Expanded.
A list item can contain state, such as a checkbox value, a text field, or an expanded/collapsed flag. Flutter must decide which existing State object belongs to each item after a rebuild. A Key gives Flutter a stable identity for that decision.
Why list items lose state
Consider a list of editable rows. If the rows are reordered, Flutter compares the new widget tree with the old one by position when no keys are present. The state from the old first row can therefore be reused for the new first row, even when the underlying data changed.
A key changes this matching rule:
- Without a key, Flutter mainly matches widgets by type and position.
- With a key, Flutter matches widgets by type and key.
- A stable key should represent the data item, not its current position.
Use a stable key in a builder
Give each stateful row a ValueKey based on a unique item ID. The ID must remain the same while the item represents the same data.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: TaskPage()));
}
class Task {
const Task(this.id, this.title);
final int id;
final String title;
}
class TaskPage extends StatefulWidget {
const TaskPage({super.key});
@override
State<TaskPage> createState() => _TaskPageState();
}
class _TaskPageState extends State<TaskPage> {
final List<Task> _tasks = const [
Task(10, 'Read the design'),
Task(20, 'Build the screen'),
Task(30, 'Test the flow'),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Tasks')),
body: ListView.builder(
itemCount: _tasks.length,
itemBuilder: (context, index) {
final task = _tasks[index];
return TaskRow(
key: ValueKey(task.id),
title: task.title,
);
},
),
);
}
}
class TaskRow extends StatefulWidget {
const TaskRow({super.key, required this.title});
final String title;
@override
State<TaskRow> createState() => _TaskRowState();
}
class _TaskRowState extends State<TaskRow> {
bool completed = false;
@override
Widget build(BuildContext context) {
return CheckboxListTile(
value: completed,
title: Text(widget.title),
onChanged: (value) {
setState(() => completed = value ?? false);
},
);
}
}If the task order later changes, Flutter uses each task ID to move the correct _TaskRowState with its task.
Choosing a key
| Key | Use |
|---|---|
| `ValueKey(id)` | A stable primitive ID, such as a number or string |
| `ObjectKey(object)` | Identity based on an object instance |
| `UniqueKey()` | A deliberately new identity; usually wrong for persistent list items |
| `PageStorageKey` | Preserving scroll or page-storage data across rebuilds |
Keys must be unique among sibling widgets. Do not use the list index when items can be inserted, removed, or reordered. An index identifies a position, not a data item.
Use UniqueKey only when you want Flutter to discard old state and create fresh state. For example, it can reset a form intentionally. For normal dynamic lists, use a stable data ID.
Exercise
A reorderable list displays users with editable text fields. Which key should each row use: ValueKey(user.id), ValueKey(index), or UniqueKey()? Why?
Show answer
Use ValueKey(user.id). The user ID remains tied to the same data item when rows move. The index changes with position, and UniqueKey forces a new state on every rebuild.