RepaintBoundary: Isolate and Optimize Flutter Painting
RepaintBoundary acts like painter's tape for your UI, isolating a widget's paint job from its parent to prevent unnecessary repaints. Use it on complex, static widgets inside an animating view. The footgun is overuse: each boundary adds memory overhead.
WHY IT EXISTS By default, when a Flutter widget needs to repaint, it can trigger a repaint of other widgets sharing its paint layer, even if they haven't changed. This is inefficient, leading to wasted CPU/GPU cycles and potential jank, especially in complex UIs with animations or scrolling.
THE MENTAL MODEL Think of a RepaintBoundary as putting painter's tape around a section of your UI. It tells Flutter's rendering engine: "This area has its own paint job. Don't repaint it just because something outside this tape changes, and don't let its changes force a repaint of the entire screen." It creates a new, independent canvas for its child.
HOW IT WORKS A RepaintBoundary widget creates a RenderObject that always has its own paint layer, decoupling it from its ancestors. When a widget inside the boundary needs to repaint, the "dirty" flag travels up the tree but stops at the boundary. The boundary itself is then scheduled to be repainted, but it doesn't trigger a repaint of its ancestors. The engine may even cache a complex, static boundary as a bitmap for faster rendering, though this is an optimization hint, not a guarantee.
WHEN TO USE IT Use RepaintBoundary when you have a widget subtree that repaints at a different frequency than its surroundings. The classic case is a complex, mostly static widget (like a chart, a custom drawing, or a QR code) inside a container that animates or scrolls. This prevents the static widget from being repainted on every frame of the parent's animation.
WHEN NOT TO USE IT Avoid wrapping simple widgets or widgets whose repaint schedule is already in sync with their parents. Creating a new paint layer has a memory and setup cost. Overusing RepaintBoundary can lead to worse performance than not using it at all. Profile your app first using tools like debugRepaintRainbowEnabled to visualize repaints and identify actual problem areas.
ONE CANONICAL EXAMPLE Flutter's Drawer widget implicitly uses a RepaintBoundary. The content inside the drawer is usually static. When you open or close the drawer, it animates its position. Without a boundary, the static content would be repainted on every frame of the slide animation. The boundary ensures the content is painted only once, and the engine just moves the resulting layer around.
Read the original → api.flutter.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.