Sub topic 8
ObjectKey and UniqueKey: when identity is not a simple value
This chapter assumes that you understand StatefulWidget, setState, lists, and the basic rule that Flutter matches widgets by runtime type and key. The key choice matters when two items look similar but represent different objects, or when you deliberately want Flutter to throw away old state.
ObjectKey uses object identity
ObjectKey identifies a widget by the identity of an object. Two ObjectKey instances match only when they refer to the same object instance.
This differs from ValueKey, which compares values with ==. Use ObjectKey when the object instance itself represents the item you want to track.
For example, a list may contain stable Person objects. Reordering the list keeps the same object instances, so each counter follows its person:
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: PeoplePage()));
}
class Person {
Person(this.name);
final String name;
}
class PeoplePage extends StatefulWidget {
const PeoplePage({super.key});
@override
State<PeoplePage> createState() => _PeoplePageState();
}
class _PeoplePageState extends State<PeoplePage> {
final List<Person> _people = [
Person('Ada'),
Person('Grace'),
Person('Linus'),
];
void _reverse() {
setState(() {
_people
..clear()
..addAll(_people.reversed);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('People'),
actions: [
IconButton(
onPressed: _reverse,
icon: const Icon(Icons.swap_vert),
),
],
),
body: ListView.builder(
itemCount: _people.length,
itemBuilder: (context, index) {
final person = _people[index];
return PersonTile(
key: ObjectKey(person),
person: person,
);
},
),
);
}
}
class PersonTile extends StatefulWidget {
const PersonTile({
super.key,
required this.person,
});
final Person person;
@override
State<PersonTile> createState() => _PersonTileState();
}
class _PersonTileState extends State<PersonTile> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return ListTile(
title: Text(widget.person.name),
subtitle: Text('Taps: $_taps'),
onTap: () => setState(() => _taps++),
);
}
}In this example, _people.reversed contains the same Person objects in a new order. The ObjectKey lets Flutter match each tile with its original element and state.
If the list is rebuilt with new Person instances, even when their names are equal, the keys do not match. Flutter treats those items as different objects. Use ValueKey(person.id) instead when a stable ID represents the same logical item across new object instances.
| Key | Matching basis | Suitable identity |
|---|---|---|
| `ValueKey<String>(person.id)` | Value equality | Stable ID or other value |
| `ObjectKey(person)` | Object identity | The same model instance |
| `UniqueKey()` | No other key matches | A deliberate reset |
UniqueKey forces a fresh identity
A UniqueKey is different from every other key, including another UniqueKey. It is useful when you want Flutter to discard a widget's existing state and create new state.
Store the key in State, then replace it when a reset is requested:
Key _editorKey = UniqueKey();
void _resetEditor() {
setState(() {
_editorKey = UniqueKey();
});
}
// In build:
Editor(key: _editorKey)When _editorKey changes, the old Editor element no longer matches. Flutter disposes its state and creates a new one. This can reset an uncontrolled text field, an animation, or another stateful subtree.
Do not write UniqueKey() directly in build unless you intentionally want to reset the subtree on every rebuild. A normal rebuild would then produce a new key, causing state loss, focus loss, and unnecessary work.
Choosing between the two
Use ObjectKey when object identity is stable and meaningful. Use ValueKey when a stable value such as a database ID identifies the item. Use UniqueKey only for an intentional reset or for items that have no reusable identity.
Keys must be placed on the top-level widget representing each item. Placing a key on an inner Text does not identify the outer stateful tile.
Exercise
A refreshed API response creates new Person objects with the same database IDs. Should a reorderable list use ObjectKey(person) or ValueKey(person.id), and why?
Show answer
Use ValueKey(person.id). ObjectKey compares object instances, so fresh objects would not match the previous ones. The stable ID preserves the logical identity across refreshes.