Sub topic 8
ObjectKey and UniqueKey: when identity is not a simple value
This chapter assumes you know how the Element tree keeps State objects between frames. It also assumes you know the matching rule (same runtimeType and same key means reuse) and how ValueKey fixes the reorder problem. If any of that is unclear, review the earlier chapters first.
ValueKey works well when each item has a simple, stable value such as an id or a unique label. Real data is often messier. Two items may share a title, the identity may be the object itself, or you may want to throw state away on purpose. ObjectKey and UniqueKey cover these cases.
Where ValueKey falls short
ValueKey<T> compares its value with ==. That makes it a good fit for strings, ints and enums. It breaks down in three situations:
- Duplicate values. Two items have the same title, so both get
ValueKey('Write'). Two siblings with equal keys cause a runtime error. - No natural id. The data is a plain object with several fields, and none of them is unique on its own.
- Overridden equality that is too loose. The class defines
==by content, so two distinct objects with the same content count as the same key.
In each case the real identity is the object instance, not a value you can read from it.
ObjectKey: identity of an object
ObjectKey(value) is a LocalKey that compares its wrapped object with identical(). Two ObjectKeys are equal only if they wrap the very same instance. The == operator on the wrapped object is never consulted.
final a = Task('Write');
final b = Task('Write');
ObjectKey(a) == ObjectKey(a); // true: same instance
ObjectKey(a) == ObjectKey(b); // false: equal titles, different instancesThe next program has two tasks with the same title. ValueKey(task.title) would throw on the duplicate, but ObjectKey(task) keeps them apart. It reuses the CounterTile from the first chapter example.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: TaskList())));
class Task {
Task(this.title);
final String title;
}
class CounterTile extends StatefulWidget {
const CounterTile({super.key, required this.label});
final String label;
@override
State<CounterTile> createState() => _CounterTileState();
}
class _CounterTileState extends State<CounterTile> {
int _count = 0;
@override
Widget build(BuildContext context) {
return ListTile(
title: Text('${widget.label}: $_count'),
onTap: () => setState(() => _count++),
);
}
}
class TaskList extends StatefulWidget {
const TaskList({super.key});
@override
State<TaskList> createState() => _TaskListState();
}
class _TaskListState extends State<TaskList> {
// The Task instances are created once and live as long as this State.
List<Task> _tasks = [Task('Write'), Task('Review'), Task('Write')];
void _reverse() {
setState(() => _tasks = _tasks.reversed.toList());
}
@override
Widget build(BuildContext context) {
return Column(
children: [
for (final task in _tasks)
CounterTile(key: ObjectKey(task), label: task.title),
TextButton(onPressed: _reverse, child: const Text('Reverse')),
],
);
}
}Tap the first tile twice and the last tile once, then press Reverse. Each counter moves with its task, even though two tiles show the same label.
Choosing between ObjectKey and ValueKey
Use ValueKey when the item has a stable id. An id from a database or server survives reloading data from the network, because the new objects carry the same id.
Use ObjectKey when the object instance is the identity. This holds when you build the list once and mutate or reorder the same objects. It stops working if you replace the objects.
Composite identity
Sometimes identity is a combination of fields. You can wrap a Dart 3 record in a ValueKey, because records have structural equality:
ValueKey((item.category, item.name))Two items are the same only if both fields match. This is often clearer than writing a custom == on the model class.
The ObjectKey trap: replaced instances
Identity-based keys follow the instance, not the data. If your code rebuilds the list from fresh objects, every ObjectKey changes and every State is lost.
// Each call produces new Task instances, so every ObjectKey is new.
List<Task> loadTasks(List<String> titles) =>
[for (final t in titles) Task(t)];Calling loadTasks inside build is the classic form of this bug. Each rebuild creates new objects, and each tile's counter resets to zero. The same happens with immutable models updated through copyWith: the copy is a different instance, so ObjectKey(copy) does not match ObjectKey(original).
The rule: if the data is replaced often (refetched, copied, deserialized), key on an id with ValueKey. If the same instances persist, ObjectKey is correct.
UniqueKey: a key equal only to itself
UniqueKey() creates a key that is not equal to any other key, including another UniqueKey(). It has no value to compare, only its own instance.
The matching rule then gives a clear result. When a widget at a given position has the same UniqueKey instance as last frame, its State is kept. When it has a different instance, Flutter discards the old Element and State and builds new ones.
That makes UniqueKey a tool for resetting state on purpose.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: ResettableCounter())));
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () => setState(() => _count++),
child: Text('Taps: $_count'),
);
}
}
class ResettableCounter extends StatefulWidget {
const ResettableCounter({super.key});
@override
State<ResettableCounter> createState() => _ResettableCounterState();
}
class _ResettableCounterState extends State<ResettableCounter> {
// Created once, kept in State, and replaced only when the user asks.
Key _counterKey = UniqueKey();
void _reset() {
setState(() => _counterKey = UniqueKey());
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Counter(key: _counterKey),
TextButton(onPressed: _reset, child: const Text('Reset')),
],
);
}
}Tap the counter a few times, then press Reset. The counter returns to zero, because the new key does not match the old Element, so Flutter builds a fresh State. The UniqueKey is stored in a field, and only the reset action replaces it.
The UniqueKey mistake in build
The most common error is writing the key inline:
// Wrong: a new key on every build.
Counter(key: UniqueKey())Every rebuild of the parent creates a new key. Flutter then sees a mismatch, disposes the old State and creates a new one. The counter resets whenever anything above it rebuilds, and you pay for destroying and recreating the subtree each time.
The same mistake appears in lists:
// Wrong: state is lost on every rebuild.
for (final label in labels) CounterTile(key: UniqueKey(), label: label)This "fixes" the reorder bug in the sense that tiles no longer show a wrong counter. It does so by throwing away all state on every rebuild, and it adds the cost of rebuilding every item's subtree. It is not a substitute for ValueKey or ObjectKey.
Where UniqueKey is legitimate
- Resetting a subtree's state on an explicit user action, as above.
- Forcing a widget to rebuild its
Statewhen an input changes in a waydidUpdateWidgetcannot handle cleanly. - Giving distinct identities to items that have none, as long as you create the keys once and store them with the data, not in
build.
Comparing the local keys
| Key | Equal when | Good for | Main risk |
|---|---|---|---|
| `ValueKey(v)` | `v == other.v` | Items with a stable id or unique value | Duplicate values cause an error |
| `ObjectKey(o)` | `identical(o, other.o)` | Items whose identity is the instance | Replaced or copied objects lose state |
| `UniqueKey()` | Same key instance only | Deliberate state reset | Created in `build`, it resets state every frame |
All three are LocalKey subclasses. They only need to be unique among siblings under the same parent, so you can reuse the same key value in different lists.
Edge cases
- Mixed key types. An
ObjectKey(x)never equals aValueKey(x), because the key classes differ. Within one collection, use one key type consistently. - Mutating a wrapped object.
ObjectKeyignores field changes, so mutating aTaskkeeps its key and itsState. This is usually what you want. It also means a stateful child must handle changed widget data itself, for example indidUpdateWidget. - Keys on the wrong widget. Like other keys, these must sit on the topmost widget of each collection item. A key on a nested child does not help Flutter match the items.
- Items without state. If every item is stateless, none of this matters. Keys protect
State, andStatelessWidgethas none.
Exercise
A list shows ListTile-based counters built from Task objects. After a network refresh, the app builds new Task instances with the same ids and titles, and every counter resets to zero. The tiles use ObjectKey(task). Why does this happen, and what is the fix?
Show answer
ObjectKey compares instances with identical(). The refresh creates new Task objects, so each key differs from the previous frame's key and Flutter builds new State objects. Key on the stable id instead, for example ValueKey(task.id). The new objects carry the same ids, so the keys match and the counters keep their values.
Exercise
A teammate writes Counter(key: UniqueKey()) inside build to "make sure the counter always shows fresh data". What is the actual effect, and how would you reset the counter only when the user presses a button?
Show answer
The key is new on every build, so Flutter discards the Counter Element and State and builds new ones on every rebuild of the parent. The counter loses its value whenever the parent rebuilds. To reset only on demand, create the key once as a field in the parent's State (Key _counterKey = UniqueKey();), pass _counterKey to Counter, and in the button handler call setState(() => _counterKey = UniqueKey()).