Flutter · One codebase, native feel

How do keys work and when do you need them?

Mediumkeyslist widgetselement identityUpdated Oct 2026
Quiz this track

Short answer

Keys give widgets identity during reconciliation. Use ValueKey or ObjectKey in reorderable and dynamic lists, and reserve GlobalKey for cases that genuinely need access across the tree.

Without a key, Flutter matches children by runtime type and position. When list items are inserted, removed or reordered, position-based matching can attach state to the wrong item. A key tells Flutter which element belongs to which logical item.

dart
ListView.builder(
  itemCount: tasks.length,
  itemBuilder: (context, index) {
    final task = tasks[index];
    return Dismissible(
      key: ValueKey(task.id),
      onDismissed: (_) => removeTask(task.id),
      child: ListTile(title: Text(task.title)),
    );
  },
)
  • ValueKey compares by value and is the default choice for list items
  • ObjectKey compares by object identity and is useful for model instances
  • UniqueKey forces a fresh element every build and is rarely appropriate
  • GlobalKey allows state access and reparenting but is expensive and easy to misuse

Where keys are required

Keys matter when the children of the same parent can change order or identity, or when state must follow an item as it moves. They are unnecessary for a fixed, static list. Two siblings must not share the same key, because that causes a duplicate-key assertion.

Do not put a GlobalKey on every row to work around state bugs. That keeps elements alive, defeats subtree disposal and can leak memory. Fix the state ownership instead.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What happens if two siblings have the same key?
  2. 2When is a GlobalKey justified?
  3. 3Why does a Dismissible require a key?
  4. 4How does changing a key affect State lifecycle?

Say it in the interview

Keys tell Flutter which element corresponds to which logical widget when the tree changes. In dynamic lists I use ValueKey with a stable id so state follows the right row after insertions, removals or reordering. GlobalKey is for the rare case where I need to reach state or move a subtree, and I avoid it in lists because it is costly and easy to leak.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Flutter mock interview and get scored feedback on depth, clarity and confidence.