Sub topic 16
Looking at the Three Trees in a Running App
This chapter assumes you can write basic Dart and compose Flutter widgets such as Row, Column, Padding, and Text. You will use Flutter’s debug output to compare the widget, element, and render object trees while an app is running.
The Three Trees
Flutter uses three related trees:
- The widget tree contains immutable configuration objects. It describes what the UI should be.
- The element tree contains long-lived objects that connect widgets to the running app. Elements manage updates and hold
Stateobjects. - The render object tree contains objects that perform layout, painting, and hit testing.
A widget does not always create a render object. For example, Padding creates a RenderPadding, and Text eventually creates a RenderParagraph. StatelessWidget, StatefulWidget, and Directionality usually compose descendants without creating their own render objects.
Dumping the Trees
The following app schedules tree dumps after the first frame:
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
void main() {
runApp(const GreetingApp());
WidgetsBinding.instance.addPostFrameCallback((_) {
debugDumpApp();
debugDumpRenderTree();
});
}
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'),
),
);
}
}Run this in a debug build and inspect the console. debugDumpApp() prints the active widget and element structure. debugDumpRenderTree() prints render objects, their constraints, sizes, and positions.
The dumps will contain more nodes than the source code. Flutter inserts framework widgets such as MediaQuery, Focus, or Semantics depending on the app environment. This is normal. Focus on the relationships rather than exact indentation.
A simplified mapping looks like this:
| Source widget | Element | Render object |
|---|---|---|
| `Padding` | `StatelessElement` | `RenderPadding` |
| `Text` | `StatelessElement` | `RenderParagraph` |
| `Directionality` | `InheritedElement` | None |
Reading Changes
When setState runs, Flutter marks the corresponding StatefulElement dirty. During the next build phase, Flutter calls build again and updates the widget configuration. The element usually remains in place, so its State also remains.
The render tree changes only when layout or painting data changes. A text change may update a RenderParagraph; changing padding may trigger layout; changing only a color may require painting without changing layout.
Exercise
Which dump should you inspect to find a render object’s size and constraints?
Show answer
Use debugDumpRenderTree(). It reports render objects and their layout information.