Keys

ValueKey, ObjectKey, GlobalKey, and when to use them

Keys preserve widget state when items move in a list. Without them, Flutter matches by position and state gets mixed up.

Keys tell Flutter which widget is which when lists are reordered, inserted, or removed. Without keys, state gets mixed up.

// WITHOUT keys: state gets confused
Column(children: [
  ColorTile(color: Colors.red),
  ColorTile(color: Colors.blue),
])
// Reorder: Flutter reuses existing widgets
// by position, mixing up internal state

// WITH keys: state follows the widget
Column(children: [
  ColorTile(key: ValueKey('red'), ...),
  ColorTile(key: ValueKey('blue'), ...),
])
With ValueKey (state preserved)
Applekey: a
Bananakey: b
Cherrykey: c
Without Key (state by position)
Appleindex: 0
Bananaindex: 1
Cherryindex: 2