Widgets and the widget tree

Learn the Flutter widget tree: StatelessWidget, StatefulWidget, setState, BuildContext, the Element and RenderObject trees, const widgets and keys. About 25 minutes.

Why it matters

  • Every Flutter screen is backed by three trees: widgets, elements and render objects. Mixing them up causes the most common Flutter bugs: setState() called after dispose(), using a BuildContext after an await, and rebuilding a whole screen because one Text changed.
  • Interviewers ask "what happens when you call setState?" and "why does const matter?" to check that you understand how Flutter reuses elements, not just the API. Android developers can map it to Compose recomposition, or to RecyclerView + DiffUtil for keys.
  • Long lists need ListView.builder so items are built lazily, and lists that reorder need keys so each item keeps its own State. Getting either wrong shows up as jank or as the wrong item showing the wrong data.
  • The render object tree is what Flutter's renderer draws. Impeller is the only renderer on iOS and the default on Android devices with Vulkan (API 29+), with older devices falling back to the legacy OpenGL renderer. Knowing where build, layout and paint happen helps you read DevTools traces.

The simple explanation

  • What is the Flutter widget tree? Widgets are immutable descriptions of UI. Each build() returns new widget objects, much like a composable function describes UI in Compose.
  • Element = the long-lived node that holds a widget's place in the tree. It keeps the State of a StatefulWidget and decides whether a new widget can update it or must replace it.
  • RenderObject = the node that does layout, painting and hit-testing. Only some elements own one (for example Padding or Text's RichText); widgets like StatelessWidgets just compose others.
  • setState = marks this element dirty. On the next frame Flutter calls build() again and updates the existing elements with the new widgets.
  • const = the same widget instance every time. If the new widget is identical to the old one, Flutter skips updating that child.
  • Key = an identity for a widget among its siblings, so Flutter can match the right element when children move.

Flutter keeps three trees. The widget tree is immutable configuration, recreated whenever build() runs. The element tree is mutable and persists across rebuilds; an element lives as long as a widget of the same type and key stays at that position, and it owns the State object. The render object tree handles layout, paint and hit-testing, and its output is what the engine rasterizes.

BuildContext is not an Android Context. It is the widget's element: Element implements the BuildContext interface. Theme.of(context) and context.findAncestorStateOfType<T>() walk up the element tree from that point. After the element is unmounted (the widget left the tree), using its context is an error, so check context.mounted (or mounted inside a State) after any await.

setState marks the element dirty. At the next frame, the framework calls build(), gets new child widgets, and for each child decides: if the new widget is identical to the old one, do nothing; if it has the same runtimeType and key, update the existing element in place; otherwise unmount the old element (and its State) and mount a new one. A const widget is the same instance on every build, so it hits the first case.

TreeMutable?LifetimeRole
WidgetNoUntil the next build() replaces itDescribes the desired UI
ElementYesWhile same type and key stay at that positionHolds State, reconciles widgets
RenderObjectYesOwned by its elementLayout, paint, hit-test

Keys matter when children of the same type move or are inserted and removed, such as reordering a list of stateful items. Without keys, Flutter matches children by position and an element (with its State) can end up paired with a different item. With ValueKey(item.id), matching follows the item. This is the same problem DiffUtil item IDs solve in RecyclerView, and key() solves in Compose LazyColumn.

Three trees, three lifetimes
Flutter's widget, element and render trees Each widget (Counter, Padding, RichText) gets a long-lived element; the StatefulElement for Counter owns its State and has no render object, while the elements for Padding and RichText own RenderPadding and RenderParagraph, which do layout and paint. WIDGET TREE new on every build() ELEMENT TREE kept across rebuilds RENDER TREE layout · paint · hit-test Counter StatefulWidget Padding RenderObjectWidget RichText leaf widget StatefulElement owns the State RenderObjectElement for Padding RenderObjectElement for RichText none Counter only composes RenderPadding adds space RenderParagraph lays out text
Widgets are rebuilt all the time, elements stay put and hold State, and only some elements own a render object.

Notes

  • Widgets are immutable. You never call a setter on a widget; you return a new one from build(). This is the opposite of the Android View model, where you call setText() on the same object, and close to how Compose works.
  • BuildContext is the widget's Element. It is valid only while that element is mounted. After an await, check if (!context.mounted) return; (or mounted in a State) before using it.
  • setState does not rebuild synchronously. It marks the element dirty, and the rebuild happens on the next frame. Several setState calls in the same frame lead to a single rebuild.
  • Calling setState after dispose() is an error. Cancel StreamSubscriptions, timers and controllers in dispose(), and check mounted after async work.
  • const widgets are canonicalized: every const Text('Tap') with the same arguments is the same instance, so Flutter skips updating it on rebuild. A widget can only be const if all its arguments are compile-time constants.
  • Flutter reuses an element when the new widget has the same runtimeType and key (Widget.canUpdate). Text('a') to Text('b') updates in place; swapping a Text for an Icon replaces the element.
  • Use ValueKey(id) or ObjectKey(item) for list items that can move. GlobalKey is unique across the whole app and lets a State move between parents or be reached from outside; it costs more, so keep it for those cases (for example a Form key).
  • ListView.builder builds items lazily as they scroll into view. A Column inside a SingleChildScrollView builds every child up front. This is the Flutter version of RecyclerView versus a long LinearLayout.
  • super.key in the constructor forwards an optional Key? to the Widget base class. Without it, callers cannot give your widget a key.
  • To see which build() methods run, enable Track widget builds in the DevTools Performance view and record a few frames in profile mode.

Code example

A StatefulWidget that loads data after an async gap with a mounted guard, uses const for static children, and shows where ValueKey belongs in a list. build() is the only place that creates widgets, and setState schedules the next build().

import 'package:flutter/material.dart';
 
class CounterPage extends StatefulWidget {
  const CounterPage({super.key, required this.label});
 
  final String label;
 
  @override
  State<CounterPage> createState() => _CounterPageState();
}
 
class _CounterPageState extends State<CounterPage> {
  int _count = 0;
 
  Future<void> _incrementLater() async {
    await Future<void>.delayed(const Duration(seconds: 1));
    if (!mounted) return; // the page may have been closed during the wait
    setState(() => _count++);
  }
 
  @override
  Widget build(BuildContext context) {
    // context is this widget's Element; Theme.of walks up from here.
    return Column(
      children: [
        Text(widget.label, style: Theme.of(context).textTheme.titleLarge),
        // New Text widget each build because _count changes.
        Text('Count: $_count'),
        ElevatedButton(
          onPressed: _incrementLater,
          child: const Text('Tap'), // same instance every build: skipped
        ),
      ],
    );
  }
}
 
class ItemList extends StatelessWidget {
  const ItemList({super.key, required this.items});
 
  final List<({int id, String name})> items;
 
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, i) => CheckboxListTileItem(
        key: ValueKey(items[i].id), // stable identity, survives reordering
        name: items[i].name,
      ),
    );
  }
}
 
class CheckboxListTileItem extends StatefulWidget {
  const CheckboxListTileItem({super.key, required this.name});
 
  final String name;
 
  @override
  State<CheckboxListTileItem> createState() => _CheckboxListTileItemState();
}
 
class _CheckboxListTileItemState extends State<CheckboxListTileItem> {
  bool _checked = false;
 
  @override
  Widget build(BuildContext context) {
    return CheckboxListTile(
      title: Text(widget.name),
      value: _checked,
      onChanged: (value) => setState(() => _checked = value ?? false),
    );
  }
}
  • if (!mounted) return; after the await prevents setState() called after dispose() when the user leaves during the delay.
  • const Text('Tap') is the same instance on every build, so Flutter skips it. The two other Text widgets are rebuilt because their arguments are not constant.
  • Each CheckboxListTileItem holds its own _checked state in its element. The ValueKey(id) makes that state follow the item when the list is reordered.
  • super.key lets the parent pass the ValueKey through to the Widget base class.

Run the idea in plain Kotlin

// A tiny model of Flutter's element reuse rules.
class Widget(val type: String, val text: String, val key: String? = null)

fun canUpdate(old: Widget, new: Widget) = old.type == new.type && old.key == new.key

fun updateChild(old: Widget, new: Widget): String = when {
  old === new -> "skip (identical, like a const widget)"
  canUpdate(old, new) -> "update element in place"
  else -> "unmount old element, mount new one"
}

// An element keeps State created from the first widget it saw.
class Element(var widget: Widget) {
  val state = "checked=" + (widget.text == "A")
}

fun reconcile(old: List<Element>, widgets: List<Widget>): List<Element> =
  widgets.mapIndexed { i, w ->
      val match = if (w.key != null) old.firstOrNull { it.widget.key == w.key } else old.getOrNull(i)
      if (match != null && canUpdate(match.widget, w)) { match.widget = w; match } else Element(w)
  }

fun main() {
  val tap = Widget("Text", "Tap")
  println("const child: " + updateChild(tap, tap))
  println("Text a -> Text b: " + updateChild(Widget("Text", "a"), Widget("Text", "b")))
  println("Text -> Icon: " + updateChild(Widget("Text", "a"), Widget("Icon", "add")))

  println("Reorder without keys:")
  val plain = listOf(Element(Widget("Item", "A")), Element(Widget("Item", "B")))
  reconcile(plain, listOf(Widget("Item", "B"), Widget("Item", "A")))
      .forEach { println("  " + it.widget.text + " " + it.state) }

  println("Reorder with keys:")
  val keyed = listOf(Element(Widget("Item", "A", "a")), Element(Widget("Item", "B", "b")))
  reconcile(keyed, listOf(Widget("Item", "B", "b"), Widget("Item", "A", "a")))
      .forEach { println("  " + it.widget.text + " " + it.state) }
}

Expected output:

const child: skip (identical, like a const widget)
Text a -> Text b: update element in place
Text -> Icon: unmount old element, mount new one
Reorder without keys:
  B checked=true
  A checked=false
Reorder with keys:
  B checked=false
  A checked=true
  • Without keys, elements are matched by position, so item B ends up with A's checked state. With keys, each state follows its item.
  • The real algorithm (Element.updateChild and updateChildren) is more involved, but these are its rules: identical widget, same type and key, or replace.

In production

setState after dispose crash in a chat screen
  • Crash reports showed setState() called after dispose() from a chat screen's message callback.
  • The screen subscribed to a Stream<List<Message>> in initState but never cancelled the subscription.
  • Messages that arrived after the user left the screen called setState on a disposed State, and the subscription kept the old State alive.
The fix
  • Stored the StreamSubscription in a field and called cancel() in dispose().
  • Kept an if (!mounted) return; guard in callbacks that run after an await.
  • Added a widget test that pumps the screen, navigates away, emits a message on the stream, and checks that tester.takeException() is null.
Whole list rebuilt on a single badge update
  • A product list stuttered whenever one item's notification badge changed.
  • The whole screen was one StatefulWidget, and the badge update called setState at the top, so every ProductTile was rebuilt.
  • DevTools with Track widget builds enabled showed every tile's build() running for a one-badge change.
The fix
  • Switched the list to ListView.builder so only visible tiles exist.
  • Gave each tile its own listener for its badge (a ValueListenableBuilder, or a provider selector) so only the changed tile rebuilds.
  • Made static children such as icons and fixed labels const, so even rebuilt tiles skip them.
  • Recorded the same interaction again in profile mode to confirm that only one tile rebuilt.

Common mistakes

  • Calling setState in an async callback without a mounted check. By the time a Future completes, the State may be disposed. Check if (!mounted) return; after the await, and cancel subscriptions and timers in dispose().
  • Forgetting const on static children. Without const, every build creates new Text, Icon and SizedBox objects and Flutter has to update their elements. Add const wherever all the arguments are constants.
  • Using a BuildContext after an await. The widget may have left the tree while you waited. Check context.mounted before calling Navigator.of(context) or showDialog, or get the Navigator before the await.
  • Reordering stateful list items without keys. Children are matched by position, so a State can end up attached to a different item. Give each item a ValueKey(id).
  • Putting the whole screen in one StatefulWidget. Every setState rebuilds the whole subtree. Split the screen into smaller widgets, or use a state-management solution so only the widgets that read the changed value rebuild.
  • Using GlobalKey for ordinary list items. A GlobalKey must be unique across the app and is meant for moving State between parents or reaching it from outside. For list identity, ValueKey or ObjectKey is enough.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What happens when you call setState in a StatefulWidget?”

“What is the difference between the Widget, Element and RenderObject trees?”

“When do you need a Key in Flutter, and which one?”

“How does const affect performance, and where do you apply it?”

Quiz

What is BuildContext in Flutter?

What does const do for a widget during a rebuild?

A list of stateful items is reordered and the items have no keys. What happens?

When does setState cause build() to run again?

0 of 4 answered

Mini task

Exercise: See which build methods run (15 min)

  1. In a Flutter project, create a StatefulWidget called RebuildProbe holding an int _tick. Its build returns a Column with three children: a StaticLabel(), a Text('tick: $_tick'), and an ElevatedButton whose onPressed calls setState(() => _tick++).

  2. Make StaticLabel a StatelessWidget with a const constructor, and put debugPrint('StaticLabel build'); inside its build. Add debugPrint('RebuildProbe build'); to RebuildProbe.build.

  3. Use it as StaticLabel() without const. Tap the button and watch the console: both messages print on every tap.

  4. Change it to const StaticLabel(). Tap again: only RebuildProbe build prints, because the child is the same instance and Flutter skips it.

  5. Run in profile mode (flutter run --profile), open DevTools, enable Track widget builds in the Performance view, and record a tap. Find the build events for RebuildProbe and check that StaticLabel is missing.

  6. Add a ListView.builder with 1,000 items, each a ListTile(key: ValueKey(i), title: Text('item $i')). Add a debugPrint in the item builder and scroll: only items near the viewport are built.

Done condition: You can explain in one sentence why const StaticLabel() does not rebuild while Text('tick: $_tick') does, and why the list builder only prints for visible items.