DEV Community

Ahmed ElFirgany
Ahmed ElFirgany

Posted on

Stop using the list index as a Flutter Key

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])
Enter fullscreen mode Exit fullscreen mode

The fix

// Right: the id belongs to the data
TaskTile(key: ValueKey(task.id), task: task)
Enter fullscreen mode Exit fullscreen mode

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)