Sub topic 3
Which widgets draw and which only compose
This chapter assumes you can write StatelessWidget and StatefulWidget classes and compose Row, Column, Padding, and Text. It also assumes you know that Flutter keeps a widget tree, an element tree, and a render object tree. Here you learn which widget classes produce render objects and which only build other widgets.
Two jobs, four base classes
A widget does one of two jobs:
- It composes: its
buildmethod returns other widgets, and nothing is laid out or painted on its behalf. - It renders: it creates a
RenderObjectthat does layout, painting, and hit testing.
Most widgets you write compose. Most widgets in the framework's core, such as Padding, Align, Row, and RichText, render. Everything you see on screen is eventually painted by a render object, but your own code rarely touches one.
The framework sorts widgets into four families, and each family has its own element type.
| Family | Base class | Element | Render object? |
|---|---|---|---|
| Stateless | `StatelessWidget` | `StatelessElement` | No |
| Stateful | `StatefulWidget` | `StatefulElement` (owns the `State`) | No |
| Proxy | `InheritedWidget`, `ParentDataWidget` | `InheritedElement`, `ParentDataElement` | No |
| Render | `LeafRenderObjectWidget`, `SingleChildRenderObjectWidget`, `MultiChildRenderObjectWidget` | `LeafRenderObjectElement`, `SingleChildRenderObjectElement`, `MultiChildRenderObjectElement` | Yes |
Stateless, stateful, and proxy elements are all ComponentElement subclasses. A component element has no render object. It only manages a child. Only RenderObjectElement subclasses own a render object.
What each family does
Composing widgets
StatelessWidget and StatefulWidget exist to build a subtree. They hold no layout logic. When you write Container(color: Colors.red, padding: EdgeInsets.all(8)), the Container itself draws nothing. Its build method assembles Padding and ColoredBox, and possibly Align, ConstrainedBox, and DecoratedBox depending on the arguments you pass. Those inner widgets render.
A composing widget costs time during the build phase and nothing during layout or paint.
Proxy widgets
A proxy widget has exactly one child and adds behavior around it without building anything new.
InheritedWidgetmakes data available to descendants. A later chapter covers how dependents are tracked.ParentDataWidget(for exampleExpanded,Flexible, andPositioned) writes data onto the render object of its nearest descendant render object widget. ARowreads that data when it lays out its children.
Directionality is an InheritedWidget, so it creates no render object. This is why the first example below has a render object for Padding but none for Directionality.
Rendering widgets
A RenderObjectWidget implements createRenderObject, which the framework calls once, when the element is mounted. It also implements updateRenderObject, which the framework calls each time the element is updated with a new widget of the same type. The three subclasses differ only in how many children they accept:
- Leaf: no child, such as
RawImage. - Single child: one child, such as
Padding,Align,SizedBox,Opacity. - Multi child: a list of children, such as
Flex(the base ofRowandColumn),Stack,RichText.
SizedBox and Center look trivial, but both are render widgets: SizedBox creates a RenderConstrainedBox and Center (an Align) creates a RenderPositionedBox.
Classifying real widgets
| Widget | Kind | What it produces |
|---|---|---|
| `Text` | Stateless | Builds a `RichText` |
| `RichText` | Multi child render | `RenderParagraph` |
| `Padding` | Single child render | `RenderPadding` |
| `Container` | Stateless | Builds `Padding`, `DecoratedBox`, and others as needed |
| `Row`, `Column` | Multi child render (through `Flex`) | `RenderFlex` |
| `Expanded` | Parent data | Sets flex data on the child's render object |
| `Directionality` | Inherited | Nothing is drawn |
| `GestureDetector` | Stateless | Builds a stateful `RawGestureDetector`, which builds a `Listener` |
| `Builder` | Stateless | Calls your builder function |
Seeing the split in a running app
You can check any widget by walking the element tree and testing whether each element is a RenderObjectElement.
import 'package:flutter/widgets.dart';
void main() {
runApp(const GreetingApp());
WidgetsBinding.instance.addPostFrameCallback((_) {
describe(WidgetsBinding.instance.rootElement!, 0);
});
}
void describe(Element element, int depth) {
final kind = element is RenderObjectElement ? 'renders' : 'composes';
debugPrint('${' ' * depth}${element.widget.runtimeType} -> $kind');
element.visitChildren((child) => describe(child, depth + 1));
}
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'),
),
);
}
}The lines for the root of the tree differ between Flutter versions. The part for your own widgets looks like this:
GreetingApp -> composes
Directionality -> composes
Padding -> renders
Text -> composes
RichText -> rendersDirectionality shows as "composes" only because the test is "is a render object element". It is a proxy element, so it does not render either.
Consequences you will notice
- Layout cost follows render objects. Wrapping a subtree in five composing widgets adds five elements but no layout work. Each extra
PaddingorAlignadds a render object that takes part in layout. - Replacing a composing widget with its parts is a refactor, not an optimization.
Containerwith only awidthandheightbuilds aConstrainedBox. UsingSizedBoxdirectly skips onebuildcall and a few intermediate widgets. This only matters in very hot paths. - Parent data has placement rules.
Expandedmust sit directly inside aFlex,Row, orColumn. If you wrap it in another widget that has its own render object, such as aPadding, the framework throws "Incorrect use of ParentDataWidget". A composing wrapper between them is fine, because theParentDataWidgetlooks for the nearest render object below it, and the check is about what lies above the render object. updateRenderObjectshould only mutate changed fields. Render object setters compare the new value with the old one and callmarkNeedsLayoutormarkNeedsPaintonly on change. The custom render object chapter relies on this pattern.
Exercise
A Column contains Expanded(child: Container(color: Colors.blue)). Which of these widgets create render objects, and which only compose or proxy?
Show answer
Column renders: it is a Flex, which creates a RenderFlex. Expanded is a ParentDataWidget, so it creates no render object. It sets flex parent data on the render object below it. Container composes. With only a color it builds a ColoredBox, which renders through its own render object (RenderColoredBox).
Exercise
In the walker above, why does Directionality print "composes" even though it has no build method of its own?
Show answer
The walker only tests element is RenderObjectElement. Directionality is an InheritedWidget, so its element is an InheritedElement, which is a ComponentElement and not a RenderObjectElement. The label "composes" means "has no render object", so proxy widgets fall under it.