Sub topic 1
Widgets, Elements and the tree Flutter keeps between frames
Prerequisites
This chapter assumes you can:
- Read and write basic Dart, including classes, constructors,
finalfields andconstconstructors. - Build simple screens with
StatelessWidgetandStatefulWidget. - Call
setStateto update a widget's state. - Use
Column,ListViewandListTilein a layout.
You don't need to know anything about keys yet. This chapter builds the mental model that explains why keys exist. Later chapters in the tutorial use it.
Why a model of the trees matters
Flutter apps are written as functions of state. Each time state changes, build runs again and returns a new description of the screen. If Flutter threw away everything and rebuilt the screen from scratch every time, scroll positions, text cursors, animations and counters would reset constantly.
Flutter avoids this by keeping a long-lived structure between frames. The build methods you write produce short-lived descriptions. The framework compares each new description with the structure it already has and updates only what changed.
To predict when your state survives and when it doesn't, you need to know which objects are recreated on every frame and which persist. That is the subject of this chapter.
The three trees
Flutter maintains three parallel trees:
- The widget tree, which holds the configuration you write.
- The element tree, which holds the live instances that manage the widgets.
- The render tree, which holds the objects that lay out and paint.
| Tree | Node type | Created by | Lifetime | Mutable? |
|---|---|---|---|---|
| Widget tree | `Widget` | Your `build` methods | One build; usually discarded the next frame | No, all fields are `final` |
| Element tree | `Element` | The framework, by calling `widget.createElement()` | Many frames, until the widget is removed from the tree | Yes, the framework changes it |
| Render tree | `RenderObject` | The framework, for widgets that draw or size things | Many frames | Yes |
Most of your work happens in the first tree. Most of the behavior that surprises developers comes from the second.
Widgets: cheap, immutable descriptions
A widget describes part of the user interface for a given configuration. Text('Hello') says "show this string here". It doesn't draw anything and doesn't remember anything. All widget fields are final, and a widget has no way to change after it is created.
Because widgets are only descriptions, creating them is cheap. A build method can create dozens of them each frame, and Flutter expects that. When setState is called, the next build returns a brand-new set of widget objects. The old ones become garbage.
This is also why a StatelessWidget is not "stateless" in the sense of having no memory anywhere. The widget object has no memory. Whatever persistent memory exists lives in another object, as the next section explains.
Elements: the persistent instances
An element is the instance of a widget at a specific location in the tree. The framework creates it the first time a widget appears at that location, by calling createElement() on the widget. The element then holds a reference to the widget that currently configures it, plus references to its parent and children.
When the parent rebuilds and provides a new widget for the same location, the framework can keep the existing element and give it the new widget. The element stays. The widget it points to changes. This is the central idea of the chapter: widgets are replaced often, and elements are replaced rarely.
Different widget types create different element types:
StatelessWidgetcreates aStatelessElement.StatefulWidgetcreates aStatefulElement. This element also creates and owns theStateobject.InheritedWidgetcreates anInheritedElement.- Widgets that produce something to draw or size, such as
Padding,RowandText(throughRichText), create aRenderObjectElement.
The BuildContext you receive in build is the element itself. The BuildContext class is an interface, and Element implements it. When you call Theme.of(context) or Navigator.of(context), Flutter walks up the element tree starting from that element.
Render objects: layout and painting
Some elements own a RenderObject. A render object knows how to measure itself against constraints, position its children and paint. Render objects are also long-lived, because layout and painting are more expensive than creating widgets. When an element receives a new widget, it updates its existing render object's properties instead of creating a new render object.
Not every widget has a render object. Container, StatelessWidget and StatefulWidget subclasses only compose other widgets, so their elements have no render object of their own. For the rest of this tutorial, the element tree is the one that matters. The render tree shows up only to explain why updating is cheaper than recreating.
Seeing the difference in code
The following program prints the identity of the widget and of its element each time a probe widget builds. In Dart, identityHashCode returns a number that identifies an object instance. Two references to the same object give the same number. In build, this is the widget, and context is the element.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Demo())));
class Demo extends StatefulWidget {
const Demo({super.key});
@override
State<Demo> createState() => _DemoState();
}
class _DemoState extends State<Demo> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
Probe(taps: _taps),
TextButton(
onPressed: () => setState(() => _taps++),
child: const Text('Rebuild'),
),
],
);
}
}
class Probe extends StatelessWidget {
const Probe({super.key, required this.taps});
final int taps;
@override
Widget build(BuildContext context) {
debugPrint(
'widget ${identityHashCode(this)} '
'element ${identityHashCode(context)}',
);
return Text('Taps: $taps');
}
}Run the app and press the button a few times. The console shows output like this. The exact numbers differ on each run.
widget 482913 element 771204
widget 120557 element 771204
widget 905331 element 771204The widget number changes every time, because _DemoState.build creates a new Probe each time. The element number stays the same. The framework saw a Probe at the same position as before, kept the existing element, and handed it the new widget. The Text below it was updated in the same way.
If Probe were created with a const constructor and no changing arguments, the same widget instance would be reused each frame. In that case the framework can skip rebuilding that part of the tree entirely, because the new widget is identical to the old one.
What happens during a frame
When you call setState, the framework doesn't rebuild the whole screen. It follows these steps:
setStateruns your callback and marks thatState's element as dirty.- At the next frame, the framework rebuilds the dirty elements. For each one, it calls
buildand gets a new widget subtree. - For each child position, the element compares the new child widget with the child element it already has.
- If the framework decides they match, it keeps the child element and updates it with the new widget. Then the same comparison runs one level down.
- If they don't match, it discards the old child element and everything below it, then creates a new element from the new widget.
The comparison in step 4 is the whole story of this tutorial. The rule that decides it uses the widget's runtime type and its key. A later chapter covers it in detail. For now, remember two facts:
- The comparison happens position by position, parent to child. It does not search the tree for a better match.
- A match preserves the element, and anything the element owns survives with it.
The following diagram shows how the three trees relate across a rebuild.
Why State lives on the element
A StatefulWidget is an immutable description like any other widget, so it can't hold a counter that persists between frames. The framework solves this by having the StatefulElement create the State object once, when the element is first mounted, and keep it for the element's whole life.
On each rebuild, the element receives the new widget and stores it in the existing State. That is why widget inside a State class always refers to the latest configuration, while fields like _count keep their values.
This gives a precise way to answer the question "will my state survive?". State survives exactly when the element that owns it survives. If the framework keeps the element, the State and its fields remain. If the framework discards the element, the State is disposed and a new one is created later with fresh default values.
You rarely notice this when the tree stays in the same shape. You notice it when you reorder, insert or remove children, because position-by-position comparison can then pair a new widget with the wrong old element. The next chapters explain the details of that problem and how keys fix it.
Common misconceptions
- "Rebuilding a widget resets its state." It doesn't. Rebuilding creates a new widget, but the existing element, and its
State, usually remain. - "A widget is the thing on the screen." A widget describes it. The element is the live instance, and the render object does the painting.
- "
constmakes state persistent."constonly means the widget instance is reused. State persistence is a property of the element. - "Calling
setStaterebuilds the whole app." It marks one element dirty. Only that element and the subtree below it are rebuilt, and only as far as the comparison finds differences. - "
BuildContextis a separate object." In practice,contextis the element, which is why each location in the tree has a different context.
Summary
Widgets are cheap, immutable descriptions that build recreates on every frame. Elements are the persistent instances the framework keeps in the tree. State objects belong to StatefulElements, and render objects belong to RenderObjectElements. Rebuilding replaces widgets and normally keeps elements. State survives when the element survives.
The next chapters cover where State lives in more detail, then the rule that decides whether the framework keeps an element.
Exercise
In the Probe example, you change _DemoState.build to return Probe(taps: _taps) when _taps is even and Text('Taps: $_taps') when _taps is odd, both in the same position of the Column. Without knowing the exact matching rule, what do you expect to happen to the element at that position when the app switches between the two, and what does that imply for any State object owned by that element?
Show answer
The two widgets have different types (Probe and Text), so they create different kinds of elements. The framework can't reuse the old element for the new widget, so it discards the old element and creates a new one. Any State owned by the discarded element is disposed, and a new element starts with fresh state. State survives only while the element survives.
Exercise
A teammate says: "My StatelessWidget is rebuilt on every setState in the parent, so Flutter must be recreating everything on screen, which is slow." Using the three trees, explain what is actually recreated and what is reused.
Show answer
Only the widget objects are recreated, and they are cheap immutable descriptions. The elements and render objects at matching positions are kept and updated with the new widgets, so layout and painting objects are not rebuilt from scratch. If a widget is const and unchanged, the framework can also skip rebuilding its subtree.