What are Keys in Flutter and when do you need one?
Short Answer
A Key preserves a widget's state and identity across rebuilds; you need one whenever Flutter could otherwise confuse two widgets of the same type at the same position, e.g. when reordering a list.
Flutter's diffing algorithm matches new widgets to old elements primarily by type and position in the tree. When widgets of the same type sit at the same index across a rebuild, Flutter assumes they're the same widget and just updates its properties, reusing the existing State object. This breaks down when a list of stateful widgets gets reordered, inserted into, or removed from — without a Key, Flutter matches by position, not identity, so state can appear to jump between items.
A ValueKey, ObjectKey, or UniqueKey tells Flutter's reconciliation exactly which old element corresponds to which new widget, based on the key's value rather than position. GlobalKey goes further, letting you access a widget's State from anywhere and preserving it even if the widget moves to a completely different part of the tree.
Code Example
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return Dismissible(
key: ValueKey(item.id), // not index — id survives reordering
onDismissed: (_) => removeItem(item),
child: ListTile(title: Text(item.title)),
);
},
)Common Mistakes
- ×Using the list index as a Key instead of a stable identifier — this defeats the purpose since the index changes when items are reordered/removed.
- ×Adding GlobalKeys everywhere 'just in case' — they're more expensive and should be reserved for cases that actually need cross-tree state access.
Interview Tips
- →Give the Dismissible/reorderable-list example specifically — it's the classic scenario where missing Keys cause visible bugs.