Flutterの key は、フレームワークがリビルドをまたいでウィジェットを正しく識別し保持するのを助けます。これは、並べ替え、追加、削除される リスト内のステートフルウィジェット において特に重要です。keyがいつ必要になるかを理解することで、微妙で分かりにくいバグを防げます。
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.).
