ValueKey<T> class
A key that uses a value of a particular type to identify itself.
A ValueKey is equal to another ValueKey if, and only if, their values are equal (using operator==).
This class can be subclassed to create value keys that will not be equal to other value keys that happen to use the same value. If the subclass is private, this results in a value key type that cannot collide with keys from other sources. This is useful when keys are used as fallbacks in the same scope as keys supplied from another widget.
When building widgets from a collection of data, especially when that collection can change over time (e.g., items being inserted, removed, or reordered), keys are used to preserve the association between a widget and the underlying data.
Without keys, the framework may have no way to distinguish between a change in the data of an existing widget and a structural change in the list. As a result, widgets may be incorrectly updated, and state held by StatefulWidgets can be reused for a different piece of data.
Assigning a key ties the widget subtree to a specific piece of data, allowing the framework to correctly match old and new widgets and preserve state as expected.
In such cases, a ValueKey is typically appropriate, using a value that is stable and unique for each item, such as an identifier from the data model.
The Key Difference
- Without Keys: When the list is reversed, Flutter matches widgets by position. The State (the counter) stays in its original spot while the widget's configuration (the color) is swapped. This results in the counter appearing to stay "stationary" while the colors move behind it.
- With Keys: By providing a ValueKey, Flutter matches the State to the Widget via the key rather than the index. When the list is reversed, the State moves with the color.
To see the difference, find the ColoredWidgetsList widget inside the map
function and comment/uncomment the key: ValueKey(color) line.
To create a local project with this code sample, run:
flutter create --sample=foundation.ValueKey.1 mysample
See also:
- Widget.key, which discusses how widgets use keys.
- ObjectKey, which uses the identity of an object as the key.
- UniqueKey, which is a key that is only equal to itself.
- Inheritance
- Implementers
Constructors
- ValueKey(T value)
-
Creates a key that delegates its operator== to the given value.
const
Properties
- hashCode → int
-
The hash code for this object.
no setteroverride
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- value → T
-
The value to which this key delegates its operator==.
final
Methods
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
override
Operators
-
operator ==(
Object other) → bool -
The equality operator.
override