Widgets and the widget tree
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 aBuildContextafter anawait, and rebuilding a whole screen because oneTextchanged. - Interviewers ask "what happens when you call
setState?" and "why doesconstmatter?" to check that you understand how Flutter reuses elements, not just the API. Android developers can map it to Compose recomposition, or toRecyclerView+DiffUtilfor keys. - Long lists need
ListView.builderso items are built lazily, and lists that reorder need keys so each item keeps its ownState. 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
Stateof aStatefulWidgetand 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
PaddingorText'sRichText); widgets likeStatelessWidgets just compose others. setState= marks this element dirty. On the next frame Flutter callsbuild()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.
| Tree | Mutable? | Lifetime | Role |
|---|---|---|---|
| Widget | No | Until the next build() replaces it | Describes the desired UI |
| Element | Yes | While same type and key stay at that position | Holds State, reconciles widgets |
| RenderObject | Yes | Owned by its element | Layout, 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.
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 AndroidViewmodel, where you callsetText()on the same object, and close to how Compose works. BuildContextis the widget'sElement. It is valid only while that element is mounted. After anawait, checkif (!context.mounted) return;(ormountedin aState) before using it.setStatedoes not rebuild synchronously. It marks the element dirty, and the rebuild happens on the next frame. SeveralsetStatecalls in the same frame lead to a single rebuild.- Calling
setStateafterdispose()is an error. CancelStreamSubscriptions, timers and controllers indispose(), and checkmountedafter async work. constwidgets are canonicalized: everyconst Text('Tap')with the same arguments is the same instance, so Flutter skips updating it on rebuild. A widget can only beconstif all its arguments are compile-time constants.- Flutter reuses an element when the new widget has the same
runtimeTypeandkey(Widget.canUpdate).Text('a')toText('b')updates in place; swapping aTextfor anIconreplaces the element. - Use
ValueKey(id)orObjectKey(item)for list items that can move.GlobalKeyis unique across the whole app and lets aStatemove between parents or be reached from outside; it costs more, so keep it for those cases (for example aFormkey). ListView.builderbuilds items lazily as they scroll into view. AColumninside aSingleChildScrollViewbuilds every child up front. This is the Flutter version ofRecyclerViewversus a longLinearLayout.super.keyin the constructor forwards an optionalKey?to theWidgetbase 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 theawaitpreventssetState() 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 otherTextwidgets are rebuilt because their arguments are not constant.- Each
CheckboxListTileItemholds its own_checkedstate in its element. TheValueKey(id)makes that state follow the item when the list is reordered. super.keylets the parent pass theValueKeythrough to theWidgetbase 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.updateChildandupdateChildren) is more involved, but these are its rules: identical widget, same type and key, or replace.
In production
- Crash reports showed
setState() called after dispose()from a chat screen's message callback. - The screen subscribed to a
Stream<List<Message>>ininitStatebut never cancelled the subscription. - Messages that arrived after the user left the screen called
setStateon a disposedState, and the subscription kept the oldStatealive.
- Stored the
StreamSubscriptionin a field and calledcancel()indispose(). - Kept an
if (!mounted) return;guard in callbacks that run after anawait. - Added a widget test that pumps the screen, navigates away, emits a message on the stream, and checks that
tester.takeException()is null.
- A product list stuttered whenever one item's notification badge changed.
- The whole screen was one
StatefulWidget, and the badge update calledsetStateat the top, so everyProductTilewas rebuilt. - DevTools with Track widget builds enabled showed every tile's
build()running for a one-badge change.
- Switched the list to
ListView.builderso 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
Futurecompletes, theStatemay be disposed. Checkif (!mounted) return;after theawait, and cancel subscriptions and timers indispose(). - Forgetting const on static children. Without
const, every build creates newText,IconandSizedBoxobjects and Flutter has to update their elements. Addconstwherever all the arguments are constants. - Using a BuildContext after an await. The widget may have left the tree while you waited. Check
context.mountedbefore callingNavigator.of(context)orshowDialog, or get theNavigatorbefore theawait. - Reordering stateful list items without keys. Children are matched by position, so a
Statecan end up attached to a different item. Give each item aValueKey(id). - Putting the whole screen in one StatefulWidget. Every
setStaterebuilds 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
GlobalKeymust be unique across the app and is meant for movingStatebetween parents or reaching it from outside. For list identity,ValueKeyorObjectKeyis 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)
-
In a Flutter project, create a
StatefulWidgetcalledRebuildProbeholding anint _tick. Itsbuildreturns aColumnwith three children: aStaticLabel(), aText('tick: $_tick'), and anElevatedButtonwhoseonPressedcallssetState(() => _tick++). -
Make
StaticLabelaStatelessWidgetwith aconstconstructor, and putdebugPrint('StaticLabel build');inside itsbuild. AdddebugPrint('RebuildProbe build');toRebuildProbe.build. -
Use it as
StaticLabel()withoutconst. Tap the button and watch the console: both messages print on every tap. -
Change it to
const StaticLabel(). Tap again: onlyRebuildProbe buildprints, because the child is the same instance and Flutter skips it. -
Run in profile mode (
flutter run --profile), open DevTools, enable Track widget builds in the Performance view, and record a tap. Find thebuildevents forRebuildProbeand check thatStaticLabelis missing. -
Add a
ListView.builderwith 1,000 items, each aListTile(key: ValueKey(i), title: Text('item $i')). Add adebugPrintin 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.