Sub topic 19
Building a custom RenderObjectWidget
This chapter builds a small leaf widget that draws a colored square. It assumes you know how widgets, elements, and render objects relate, what markNeedsLayout and markNeedsPaint do in the frame pipeline, and the "constraints down, sizes up, parent sets position" layout rule. You should also be comfortable with Dart setters and cascades.
When to write one
Most custom visuals do not need a new render object. Composing existing widgets, or drawing with CustomPaint, covers most cases. Write a RenderObjectWidget when you need control over layout, painting, and hit testing together. Examples are a new layout algorithm, a widget that must report its own intrinsic size, or a painter that must skip layout when only its color changes.
Two classes are always involved:
- The widget is an immutable configuration. It creates the render object once and pushes new configuration into it on later rebuilds.
- The render object is long-lived. It owns the layout and paint logic and decides what work a change requires.
For a widget with no children, extend LeafRenderObjectWidget. Its element is a LeafRenderObjectElement, so you write no element code.
The widget half
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
class ColoredSquare extends LeafRenderObjectWidget {
const ColoredSquare({super.key, required this.color, this.side = 48});
final Color color;
final double side;
@override
RenderObject createRenderObject(BuildContext context) =>
RenderColoredSquare(color, side);
@override
void updateRenderObject(
BuildContext context, RenderColoredSquare renderObject) {
renderObject
..color = color
..side = side;
}
}createRenderObject runs when the element is mounted. updateRenderObject runs each time the parent rebuilds and Widget.canUpdate lets the existing element take the new widget. The widget does not compare old and new values. It assigns every field and lets the render object's setters decide what to do.
The BuildContext argument is the element. You can read inherited values from it, such as Directionality.of(context). If you do, you must also re-read them in updateRenderObject.
The render object half
class RenderColoredSquare extends RenderBox {
RenderColoredSquare(this._color, this._side);
Color _color;
double _side;
set color(Color value) {
if (value == _color) return;
_color = value;
markNeedsPaint();
}
set side(double value) {
if (value == _side) return;
_side = value;
markNeedsLayout();
}
@override
void performLayout() {
size = constraints.constrain(Size.square(_side));
}
@override
void paint(PaintingContext context, Offset offset) {
context.canvas.drawRect(offset & size, Paint()..color = _color);
}
}Each member has a specific job:
- Setters compare first and return early when nothing changed. Then they mark only the phase that is affected.
performLayoutreceivesconstraintsfrom the parent. You must assignsize, and the size must satisfy the constraints.constraints.constrainclamps the preferred size into the allowed range. If you skip it and the parent passes tight constraints, Flutter asserts in debug mode.paintdraws atoffset, which is this object's position in its parent's coordinate space. The parent set that position during its own layout. Drawing atOffset.zerois a common bug, and it puts every instance at the top-left of the parent.
Run it
void main() {
runApp(const Center(child: ColoredSquare(color: Color(0xFF2196F3))));
}Center loosens the constraints. The root receives tight screen-sized constraints, so without Center the square would be forced to fill the screen. Your preferred side is a request. The parent's constraints decide the outcome.
Choosing what to mark
The two setters mark different work. A color change cannot alter the size, so only repaint is needed. A side change may alter the size, which can affect the parent's layout, so layout is needed.
The rule: mark layout when a value can change size or child positions, and mark paint when it changes only pixels. Marking too little leaves stale output. Marking too much wastes frame time but is still correct.
Edge cases and gotchas
- Hit testing. A
RenderBoxignores pointer events on itself by default. If the square must receive taps, overridehitTestSelf(Offset position) => true. Wrapping it in aGestureDetectoralso works, because the detector's own render object handles hits. - Sizing without constraints. If a parent passes unbounded constraints,
constrainstill returns a finite size here becausesideis finite. A widget that sizes itself from the constraints, such asconstraints.maxWidth, must handledouble.infinity. sizedByParent. If size depends only on constraints, overridesizedByParent => trueand implementcomputeDryLayout. Layout then skips re-running when only unrelated state changes. This square depends on_side, so it does not qualify.- Intrinsic sizes and baselines. Widgets like
IntrinsicWidthcall methods such ascomputeMinIntrinsicWidth. If you do not override them, the defaults return 0. Override them if your widget may sit inside those parents. - Allocation in
paint. The example creates aPaintper call for clarity. For heavy painting, cache it in a field and update its color in the setter. - Repaint isolation. A render object that repaints often, such as an animated one, can set
isRepaintBoundary => trueso its repaints do not dirty its ancestors' layers. Add this only after measuring.
| Symptom | Likely cause |
|---|---|
| Square draws at the wrong place | `paint` ignored `offset` |
| Color change does not appear | Setter updated the field but did not call `markNeedsPaint` |
| Size change does not appear | Setter called `markNeedsPaint` instead of `markNeedsLayout` |
| Debug assertion about size | `performLayout` did not set `size`, or set one outside the constraints |
| Taps do nothing | `hitTestSelf` not overridden |
Verify it in the render tree
Add debugDumpRenderTree() in a post-frame callback, as in the earlier debugging chapter. The output contains a RenderColoredSquare node under RenderPositionedBox (from Center). Its entry shows the constraints it received and the size it chose. Comparing those two lines is the fastest way to confirm that the parent's constraints, not your side, decided the result.
Exercise
You add a Color getter-less setter set cornerRadius(double value) to RenderColoredSquare and paint with drawRRect. Which method should the setter call when the value changes, and why?
Show answer
It should call markNeedsPaint. The corner radius changes only how the square is drawn. It does not change the size or any child positions, so layout does not need to run again.
Exercise
A ColoredSquare(side: 200) is placed directly as the home of a root app with tight screen-sized constraints. Its size comes out equal to the screen. Which line of code causes this, and how do you get a 200-pixel square?
Show answer
constraints.constrain(Size.square(_side)) in performLayout clamps 200 into the tight constraints, so the parent's constraints win. Wrap the widget in something that loosens constraints, such as Center or Align. Then the clamp allows 200.