Sub topic 13
Keys and Preserving State
Assume you know basic Dart classes, constructors, final fields, named parameters, and null safety. You also need a Flutter installation that can run a simple app.
A StatefulWidget keeps its changing data in a separate State object. Flutter must decide which existing State object belongs to each widget after a rebuild. A key helps Flutter make that decision.
How Flutter matches widgets
Flutter compares the new widget tree with the previous tree. For children with the same parent, it normally matches widgets by their position and type. A key adds a stable identity to that match.
Keys matter when a list changes order, items are inserted, or items are removed. Without keys, state can remain attached to a position instead of the item that originally owned it.
A key is local when it only needs to be unique among siblings with the same parent. ValueKey is usually the right choice for list items because it compares values such as database IDs.
| Key type | Typical use | Effect |
|---|---|---|
| `ValueKey(id)` | Stable item identity | Preserves state for that ID |
| `ObjectKey(object)` | Identity of a specific object | Matches the same object instance |
| `UniqueKey()` | Force a fresh identity | Usually creates new state |
| `GlobalKey` | Rare cross-tree identity | Can move or access a widget's state |
Preserving state in a list
This complete example displays a counter inside each todo item. Press Reverse to reorder the list. Because every tile has a key based on its stable ID, each counter stays with its todo.
import 'package:flutter/material.dart';
void main() {
runApp(const TodoApp());
}
class Todo {
const Todo(this.id, this.title);
final int id;
final String title;
}
class TodoApp extends StatelessWidget {
const TodoApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: const TodoListPage(),
);
}
}
class TodoTile extends StatefulWidget {
const TodoTile({
super.key,
required this.todo,
});
final Todo todo;
@override
State<TodoTile> createState() => _TodoTileState();
}
class _TodoTileState extends State<TodoTile> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return ListTile(
title: Text(widget.todo.title),
subtitle: Text('Taps: $_taps'),
trailing: IconButton(
icon: const Icon(Icons.add),
onPressed: () {
setState(() {
_taps++;
});
},
),
);
}
}
class TodoListPage extends StatefulWidget {
const TodoListPage({super.key});
@override
State<TodoListPage> createState() => _TodoListPageState();
}
class _TodoListPageState extends State<TodoListPage> {
List<Todo> _todos = const [
Todo(1, 'Read about widgets'),
Todo(2, 'Practice keys'),
Todo(3, 'Run the example'),
];
void _reverseTodos() {
setState(() {
_todos = _todos.reversed.toList();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Todos'),
actions: [
IconButton(
onPressed: _reverseTodos,
icon: const Icon(Icons.swap_vert),
),
],
),
body: ListView(
children: [
for (final todo in _todos)
TodoTile(
key: ValueKey(todo.id),
todo: todo,
),
],
),
);
}
}The Todo ID is stable even when the list position changes. The key therefore tells Flutter that the tile for ID 2 is still the same tile.
Resetting state deliberately
Changing a widget's key tells Flutter that it has a different identity. Flutter can then discard the old State object and create a new one. This is useful when a form should reset for a new record.
UniqueKey() creates a new key each time the widget is built, so it can reset state repeatedly. Use it deliberately. A changing key can also discard text entered by a user.
GlobalKey has wider scope and more work for Flutter. Use it only when you need capabilities such as moving a stateful widget between parts of the tree or accessing its state from elsewhere. Prefer local keys for list identity.
Exercise
A stateful list item shows the wrong counter after the items are reordered. What should you check first?
Show answer
Give each item a stable local key, such as ValueKey(item.id), and make sure the ID does not change when the item moves.