Key 在 Flutter 中帮助框架在重建期间正确识别和保留 widget — 对于列表中的 stateful widget 特别重要,这些 widget 可能被重新排序、添加或移除。理解何时需要 key 可以防止细微且令人困惑的 bug。
Key 的作用
During rebuilds, Flutter MATCHES new widgets to existing elements/state by POSITION and
TYPE. Usually this works fine. But when widgets of the SAME TYPE are reordered/added/
removed in a list, position-matching gets confused → state attaches to the WRONG widget.
→ KEYS give widgets a stable IDENTITY so Flutter matches them correctly across changes.
经典问题(没有 key)
A list of STATEFUL widgets (e.g. items with their own state). You remove the FIRST item:
✗ WITHOUT keys → Flutter matches by position → the state stays at each position, so
state appears attached to the WRONG items (state "shifts" incorrectly)
✓ WITH keys → Flutter matches by key → state follows the correct widget
→ This causes confusing bugs (wrong checkbox checked, wrong item highlighted, etc.).
