Diagnosing and fixing CustomPainter jank
optimizing custom canvas rendering.
avoid work in paint, gate repaints with shouldRepaint, isolate with RepaintBoundary, cache static layers.
blaming the device or repainting everything every frame.
WHAT THIS TESTS Whether you can reason about the paint pipeline, measure rather than guess, and apply targeted fixes to custom rendering hot paths.
A GOOD ANSWER COVERS Common causes: doing layout math, allocating Paint or Path objects, or loading images inside paint, which runs every frame; returning true from shouldRepaint so the painter repaints even when nothing changed; expensive Canvas calls like saveLayer, blur filters and large paths repeated each frame; and overdraw from stacking opaque layers. Fixes: precompute and cache Paint and Path objects in fields, implement shouldRepaint to compare only the inputs that actually changed, wrap the painting widget in a RepaintBoundary so its layer is isolated and neighbors do not force it to repaint, and cache static content by recording a ui.Picture or rasterizing to an image once and reusing it.
COMMON WRONG ANSWERS Guessing without the DevTools performance overlay or timeline. Always returning true from shouldRepaint. Wrapping everything in RepaintBoundary indiscriminately, which adds memory and composition cost. Confusing repaint with relayout.
LIKELY FOLLOW-UPS What does RepaintBoundary actually isolate. When is saveLayer unavoidable. How do you read the raster versus UI thread split in the timeline. Costs of too many layers.
ONE CONCRETE EXAMPLE A charting widget redraws a 2000-point line plus a moving crosshair every frame, allocating a new Path each time. The timeline shows the raster thread spiking. The fix splits it: the static line goes in its own painter inside a RepaintBoundary with a precomputed Path and shouldRepaint returning false, while only the crosshair painter repaints as the pointer moves. Caching the line as a ui.Picture removes the per-frame path rebuild and the jank disappears.
Read the original → plugfox.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.