D
Flutter CoreIntermediate30 XP5 min read

What are Keys in Flutter and when should you use them?

TL;DR: Keys help Flutter's reconciliation algorithm identify widgets when they move within the tree. Use LocalKeys (ValueKey, ObjectKey, UniqueKey) for list items, and GlobalKey only when you need cross-tree element access.

Full Answer

Without keys, Flutter identifies widgets by their position in the tree. When widgets reorder (e.g., in a list), Flutter can match wrong elements to wrong widgets, causing visual glitches or lost state.

ValueKey

Uses a value for comparison. Ideal for list items with stable, unique IDs: ValueKey(item.id). Two ValueKeys are equal if their values are equal.

ObjectKey

Uses object identity (same reference). Use when objects don't implement == by value: ObjectKey(item).

UniqueKey

Creates a new unique key each time. Useful to force-rebuild a widget: UniqueKey() as a key will always create a fresh element.

GlobalKey

References a specific element across the entire tree. Use sparingly — only for FormState.validate(), ScaffoldState.openDrawer(), or moving widgets between different subtrees. GlobalKey is expensive.

⚠️

Never generate keys in build() — e.g., UniqueKey() in a list item means every rebuild creates a new key, forcing full subtree reconstruction. Generate keys once and store them.

Code Examples

dartKeys in action with reorderable list
Output
With ValueKey: checkbox states follow their items when list is shuffled.
Without keys: checkbox states stay in their positions (wrong behavior).

Interview Tip

💡

The most common interview question about Keys: 'Why does my list lose state when I reorder?' — answer is missing ValueKey on list items. The reconciliation algorithm uses key + runtimeType to match elements.

#keys#valuekey#objectkey#uniquekey#globalkey#reconciliation