You delete the first item in a list. The checkmark jumps to the next item.
Nothing is wrong with your data. The bug is in the key.
The bug
// Wrong: the index changes after every delete
TaskTile(key: ValueKey(index), task: tasks[index])
The fix
// Right: the id belongs to the data
TaskTile(key: ValueKey(task.id), task: task)
Why it happens
Flutter matches old widgets to new ones by type and position.
The state lives in the element, not in the widget.
Delete the first item, and the second one takes its place. It also inherits the first one's state.
A stable key from the data stops that.
When you need it
Only when list children hold state and the list can reorder or delete. Checkboxes, text fields and animations are the usual cases.
A static stateless list does not need keys.
The rule: a key is the item's identity, not its place.
Short video version (Arabic voice-over, English terms): https://youtube.com/shorts/DhvVwhrKREI
Top comments (0)