Sobes.tech
Junior — Middle

Explain the concept of keys in Flutter and their role in widgets.

sobes.tech AI

Answer from AI

In Flutter, Keys are used to identify widgets, state elements, and objects in the widget tree. They help Flutter correctly match old and new widgets during interface rebuilds, especially when the order or number of widgets changes.

Role of keys:

  • Preserve widget state during rebuilds
  • Ensure widget uniqueness in lists or collections

Example of using a key:

ListView(
  children: items.map((item) => ListTile(
    key: ValueKey(item.id),
    title: Text(item.name),
  )).toList(),
)

Here, ValueKey with a unique item.id helps Flutter understand which element has changed and which remains the same, improving performance and preventing state loss.