Sub topic 4
Elements: the living tree behind your widgets
This chapter assumes you can write StatelessWidget and StatefulWidget classes and compose Row, Column, Padding, and Text. It also assumes you know that widgets are immutable descriptions. Here you meet the second tree, the one that holds the running app together.
Why a second tree exists
Widgets are cheap. A parent's build method creates new widget objects on every rebuild, and Flutter discards the old ones. Something has to stay alive across those rebuilds to remember where each widget sits, which State belongs to it, and which render object it controls. That something is the element.
An element is a long-lived object created from a widget. It is the widget's instance in the tree. The widget says "show a Padding of 16 with this child". The element is the actual Padding that exists on screen right now.
Each element keeps:
- A reference to its current widget, which is replaced when the parent supplies a new configuration.
- A reference to its parent element and its child elements.
- Its depth in the tree and its slot, meaning its position among its siblings.
- Some elements also hold a
Stateobject (stateful elements) or a render object (render object elements).
The tree is built by inflation
When Flutter needs to show a widget for the first time, it calls widget.createElement(). It then mounts the element into the tree, and the element asks its widget for children. This process is called inflating. Each child widget gets its own element, and so on down the tree.
Every widget class decides which element type it creates:
| Widget kind | Element class | Owns a render object? |
|---|---|---|
| StatelessWidget | StatelessElement | No |
| StatefulWidget | StatefulElement | No, but it owns the State |
| InheritedWidget | InheritedElement | No |
| LeafRenderObjectWidget | LeafRenderObjectElement | Yes |
| SingleChildRenderObjectWidget | SingleChildRenderObjectElement | Yes |
| MultiChildRenderObjectWidget | MultiChildRenderObjectElement | Yes |
Only the last three rows create render objects. The other kinds compose widgets and add no layout or painting of their own.
Mapping one small app
Here is the widget tree from the topic's first example.
import 'package:flutter/widgets.dart';
void main() => runApp(const GreetingApp());
class GreetingApp extends StatelessWidget {
const GreetingApp({super.key});
@override
Widget build(BuildContext context) {
return const Directionality(
textDirection: TextDirection.ltr,
child: Padding(
padding: EdgeInsets.all(16),
child: Text('Hello'),
),
);
}
}Each widget gets an element. Only some of them also get a render object:
GreetingAppgets a StatelessElement. It builds the Directionality and creates no render object.Directionalityis an InheritedWidget, so it gets an InheritedElement. It makes the text direction available to descendants and creates no render object.Paddingis a SingleChildRenderObjectWidget. Its element creates a RenderPadding.Textgets a StatelessElement. It builds aRichText, and that widget's element creates a RenderParagraph.
The element tree has one element per widget in this chain. The render tree is shorter, because GreetingApp, Directionality, and Text add nothing to it.
Widgets and elements are not one to one
One widget object can be inflated more than once. A const widget is a single shared instance. If you place the same const Text('Hello') in two places, Flutter creates two elements that both point at that one widget. The reverse also happens. An element outlives many widget objects, because each rebuild hands it a fresh widget.
This is why you should not store per-instance data on a widget. The widget is a description. The element, and for stateful widgets the State, holds the instance data.
Updating in place
When a parent rebuilds, it produces a new widget for each child slot. Flutter does not throw away the child element straight away. It first asks whether the existing element can take the new widget:
// Paraphrase of the rule in Flutter's Widget class.
static bool canUpdate(Widget oldWidget, Widget newWidget) {
return oldWidget.runtimeType == newWidget.runtimeType &&
oldWidget.key == newWidget.key;
}If both the runtime type and the key match, the element stays. It stores the new widget and updates its children. For a render object element, this also pushes the new configuration to the render object, so layout and paint state survive. If either differs, the old element is dropped, and a new element is inflated from the new widget. A later chapter covers this decision in detail, including what happens with lists of siblings.
The practical result is that an element's identity depends on its type, key, and position. That is why a State survives a rebuild: it hangs off an element that was kept.
Seeing an element from your code
You rarely touch elements directly. The BuildContext that build receives is the element itself, exposed through a limited interface. You can confirm this in debug code:
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
class WhoAmI extends StatelessWidget {
const WhoAmI({super.key});
@override
Widget build(BuildContext context) {
final element = context as Element;
debugPrint(
'${element.runtimeType} for ${element.widget.runtimeType}, '
'depth ${element.depth}',
);
return const SizedBox();
}
}This prints StatelessElement for WhoAmI followed by the element's depth. Treat the cast as a learning tool only. Production code should use the BuildContext methods, such as Theme.of(context), which walk the element tree for you.
Common mistakes
- Expecting widget identity to persist. Comparing widget instances across rebuilds tells you nothing useful. Flutter will almost always give you new ones. The element is what persists.
- Assuming every widget draws. Many widgets only compose. If you wonder why a widget has no effect on layout, check whether it creates a render object.
- Holding data on the widget that should live in State. Widgets are recreated constantly, so anything you mutate on them is lost or duplicated.
- Confusing the tree depth of the three trees. The element tree is usually deeper than the render tree, as the diagram shows.
Exercise
You write const Text('Hi') once and use that same constant in two places in a Column. How many Text widget objects exist, and how many elements does Flutter create for them?
Show answer
One widget object exists, because a const expression yields a single shared instance. Flutter creates two elements, one for each place in the tree, and both elements point at that same widget.
Exercise
In the GreetingApp example, which of GreetingApp, Directionality, Padding, and Text create a render object of their own, and which render objects are created?
Show answer
Only Padding creates one directly, a RenderPadding. Text does not create a render object itself, but the RichText it builds does, a RenderParagraph. GreetingApp and Directionality create none.
Exercise
A parent rebuilds and gives a child slot a Padding where it previously had a Padding with a different padding value and no key. Does Flutter keep or replace the child element, and why?
Show answer
It keeps the element. The runtime type (Padding) and the key (null) are both unchanged, so Widget.canUpdate returns true. The element takes the new widget and updates its render object with the new padding value.