D
Widget TreeIntermediate30 XP3 min read

When and why should you use Keys in Flutter?

TL;DR: Keys help Flutter's reconciliation algorithm match elements to widgets when the widget type stays the same but the identity changes — essential when reordering lists or preserving state across rebuilds.

Full Answer

Flutter uses widget type and position to match elements during reconciliation. Without keys, swapping two same-type widgets keeps the old element (and its state) in place.

Types of Keys

  • ValueKey — identity based on a value (e.g., item id). Use for list items.
  • ObjectKey — identity based on an object reference.
  • UniqueKey — always different; forces element recreation every build.
  • GlobalKey — allows accessing a widget's State and RenderObject from anywhere in the tree.
  • PageStorageKey — preserves scroll position across tab switches.
🎯

GlobalKey is powerful but expensive. Avoid using it as a general state-sharing mechanism — prefer InheritedWidget or a state-management library instead.

Code Examples

dartUsing ValueKey in an animated list
Output
Each list item is uniquely identified; swiping removes the correct item even after reorder

Common Mistakes

  • Using UniqueKey() in build() — recreates the widget on every rebuild, destroying state
  • Not using keys in AnimatedList or ReorderableListView, causing state to migrate to wrong items

Interview Tip

💡

The classic interview demo: two ColoredBox widgets swapping positions. Without keys, state stays with the position. With ValueKey, state follows the widget.

#keys#GlobalKey#ValueKey#UniqueKey#element-tree