FlutterBasic 2 min read

BuildContext and keys: location versus identity

Distinguish a widget location from its identity, and use stable keys when stateful rows can move.

On this page

BuildContext represents a location in the element tree. APIs such as Theme.of and Navigator.of use that location to find an ancestor. A key helps the framework match a widget with an existing element during an update. They solve different problems.

Find ancestors from the right location

A context created above a provider or Scaffold cannot look downward into that new child. Introduce a child widget or Builder when you need a context below a newly created ancestor.

Preserve list identity

If users can reorder stateful rows, use a stable value from the data as a key. An index describes the current position and changes when the item moves. A new UniqueKey on every build deliberately discards the previous identity.

The fragment assumes tasks have stable IDs and that TaskTile is defined in the project.

Worked example

This is a focused code fragment. Place it in the class or file described above; it is not a complete standalone app.

ListView(children: [
  for (final task in tasks)
    TaskTile(key: ValueKey(task.id), task: task),
])

Read the result

The key follows the task ID rather than its current index. Use a GlobalKey only for capabilities that require it, not as a universal way to share state.

Use location and identity to answer different questions

When Theme.of(context) runs, the framework uses that context’s place in the tree to find an inherited theme above it. Giving the widget a key does not change which ancestor is visible. Conversely, a valid context does not automatically give a reordered row the identity of its underlying data item.

Imagine two text-editing task rows swap positions. An index key says “the item at position zero”, so it can preserve state for a position rather than for the task the user meant. A stable task-ID key says “this specific task”, even when it moves.

Use the context below a newly introduced ancestor when looking up its services. Use stable data identity when matching stateful siblings. The shared-state example and task-list project provide places to practise these ideas independently.

Practice and verification

Build two editable rows, enter different text and swap their order. Compare no key, an index key and a stable item-ID key. Explain which identity you want to preserve.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.