Sub topic 10
Render objects: layout, painting, and hit testing
This chapter assumes you know the widget and element trees from the earlier chapters. You should know that an element is the long-lived instance for a widget, and that RenderObjectWidget is the kind of widget that has a render object. Here we look at the third tree: what a render object stores and which three jobs it does.
What a render object is
A render object is a long-lived Dart object that knows its size, its position relative to its parent, how to draw itself, and whether a pointer touch lands on it. A RenderObjectElement creates it when the element mounts. The element calls updateRenderObject on the widget whenever the widget is replaced by a new configuration. The render object itself survives rebuilds, which is why changing a Padding value does not allocate a new RenderPadding.
Most render objects extend RenderBox, which uses a rectangular box protocol: constraints are a BoxConstraints and the result is a Size. A RenderBox with children stores a parentData object on each child, and the parent writes the child's offset there. Widgets such as Padding, Align, Stack, and Text (through RichText) each map to a different RenderBox subclass. Widgets like StatelessWidget and Directionality produce none, so they are invisible in the render tree.
The three jobs below run in a fixed order each frame, and each job can be invalidated on its own.
| Job | Method you override | Marked dirty by | Runs in |
|---|---|---|---|
| Layout | `performLayout` | `markNeedsLayout` | layout phase |
| Painting | `paint` | `markNeedsPaint` | paint phase |
| Hit testing | `hitTestSelf`, `hitTestChildren` | not cached; runs per pointer event | on pointer down |
Layout: constraints down, sizes up
The parent calls child.layout(constraints, parentUsesSize: true). The child picks a size inside those constraints and assigns it to size in performLayout. The parent then decides where the child goes by setting the child's parentData.offset. A child never positions itself.
Three points matter in practice:
- Tight and loose constraints. A tight constraint has equal min and max, so the child has no choice. A loose constraint has a minimum of zero, so the child can be anything up to the maximum.
constraints.constrain(size)clamps a preferred size into the allowed range. - Unbounded constraints. A
Columngives its children an infinite maximum height. A child that tries to fill the available height, such as aListView, then fails with a "vertical viewport was given unbounded height" error. The fix is to give the parent a bounded height, for example withExpanded. parentUsesSize. If the parent readschild.size, it must passparentUsesSize: true. The framework then also relayouts the parent when the child's size changes. If the parent ignores the size, the child becomes a relayout boundary and the change stays local. Boundaries get their own chapter.
When a property that affects size changes, the render object's setter compares the new value and calls markNeedsLayout. This adds the object to the PipelineOwner's dirty list. Layout runs top-down once in the next frame, only on dirty subtrees.
Painting
paint(PaintingContext context, Offset offset) receives the object's origin in the coordinate space of the current layer. A render object draws itself with context.canvas, then paints its children with context.paintChild(child, offset + childParentData.offset). Children are painted in order, so later children appear on top.
Painting never changes size. If only a color changes, call markNeedsPaint and skip layout. This is why the render object setters in the previous section distinguish the two calls. Calling markNeedsLayout for a color change works, but it does extra work for nothing. Calling only markNeedsPaint for a size change leaves the parent with a stale size. That is the more serious error.
The paint phase does not draw pixels directly. It records drawing commands into layers, and the compositing phase combines them. That belongs to the layer tree chapter.
Hit testing
When a pointer goes down, the gesture binding asks the root of the render tree to build a hit test result. The root calls hitTest(result, position: position) where position is in that object's own local coordinates. A RenderBox answers in these steps:
- If the position is outside
size, returnfalse. - Call
hitTestChildren. Children are tested in reverse paint order, so the front-most child gets the first chance. Before testing a child, the parent converts the position into the child's coordinates by subtractingparentData.offset. - If no child was hit, call
hitTestSelf. By default this returnsfalse. - If either returned
true, the object adds aHitTestEntryfor itself to the result.
The result is a path of entries from the deepest object up to the root. The binding sends the pointer event to each entry, and gesture recognizers compete from there.
Because hitTestSelf returns false by default, empty space does not respond. Padding is the usual surprise. Its own area is not hit unless a child covers the point. The GestureDetector property behavior controls this. With the default deferToChild, only the child's area counts. With HitTestBehavior.opaque, the detector claims its whole box.
The following program shows the effect of hitTestSelf on a padded child. Tap the text, then tap the empty padding. Change behavior to HitTestBehavior.deferToChild and the padding stops responding.
import 'package:flutter/widgets.dart';
void main() => runApp(const HitDemo());
class HitDemo extends StatefulWidget {
const HitDemo({super.key});
@override
State<HitDemo> createState() => _HitDemoState();
}
class _HitDemoState extends State<HitDemo> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => setState(() => _taps++),
child: Padding(
padding: const EdgeInsets.all(48),
child: Text('Taps: $_taps'),
),
),
),
);
}
}Common errors
- "RenderBox was not laid out." Code read
sizebefore the object's layout ran. Read it only insideperformLayoutafter callingchild.layout, or after layout completes. - Assigning
sizeoutside layout. Set it inperformLayoutor throughsizedByParent. Elsewhere it breaks the dirty tracking. - Setter without a mark call. A new value is stored but nothing reruns, so the screen looks unchanged.
- Painting outside the box.
paintcan draw anywhere on the canvas. That does not enlarge the hit test area, which still followssize. - Unhittable transparent areas. A
Containerwith no color and no child behaves like empty space. Add a color or useHitTestBehavior.opaque.
Exercise
A RenderBox subclass changes its color field in a setter and calls markNeedsLayout. The screen updates correctly. Why is this still a mistake, and which call is better?
Show answer
The color does not affect size, so layout work is wasted. markNeedsLayout also schedules a paint, so the output is right, but it forces a layout pass on this subtree and possibly on its parent. markNeedsPaint is the correct call and reruns only the paint phase.