Sub topic 3
ObjectKey, UniqueKey, and Other Ways to Keep State
This section assumes you can write a StatefulWidget, call setState, and build lists with ListView or Column. You should also know that Flutter matches widgets to existing State by type and key, as covered in the earlier chapters.
ObjectKey and UniqueKey
ObjectKey identifies a widget by an object's equality (==), so use it when each list item wraps a model object that has a stable identity. UniqueKey never equals any other key, so it forces Flutter to discard the State every time it builds.
ListView(
children: [
for (final todo in todos)
TodoTile(key: ObjectKey(todo), todo: todo),
],
)PageStorageKey
A PageStorageKey saves a scrollable's scroll offset in the nearest PageStorage bucket. Routes and Scaffold provide that bucket, so the position survives when the list is removed and rebuilt.
GlobalKey
A GlobalKey is unique across the whole app. Use it to reach a State from outside its subtree, such as calling validate() on a Form:
final _formKey = GlobalKey<FormState>();
Form(key: _formKey, child: ...);
if (_formKey.currentState!.validate()) {
// Save the form.
}A GlobalKey can also move a widget to a new parent in the same frame while keeping its State.
AutomaticKeepAliveClientMixin
Lazy parents such as TabBarView and ListView dispose off-screen children. Mix in AutomaticKeepAliveClientMixin, return true from wantKeepAlive, and call super.build(context) to keep the State alive.
Pitfalls
Duplicate keys among siblings throw an error at runtime.
Creating keys inside build with UniqueKey() or GlobalKey() discards State on every rebuild. GlobalKey also adds bookkeeping cost, so reserve it for cases that need it.
Choosing an Approach
Exercise
Exercise
Why does key: UniqueKey() inside build cause the tile's State to reset on every rebuild?
Show answer
Each build creates a new key that matches no previous element, so Flutter discards the old State and creates a new one.