tezvyn:

CustomPaint: Drawing Your Own Widgets in Flutter

AI-drafted, machine-checkedSource: api.flutter.devintermediate

CustomPaint is your blank canvas widget; CustomPainter is the artist that draws on it. Use them for custom charts or unique UI. The footgun: shared canvases can cause blend modes to erase other widgets, so use `saveLayer` sparingly.

WHY IT EXISTS Flutter's widget library is extensive, but sometimes you need a visual element that doesn't exist. Instead of composing many widgets, CustomPaint provides a low-level, high-performance escape hatch to draw exactly what you need, from simple shapes to complex data visualizations.

THE MENTAL MODEL Think of CustomPaint as a widget that carves out a rectangular space on the screen and gives you a blank Canvas. CustomPainter is a separate class where you define the drawing logic. You create your painter, pass it to the CustomPaint widget, and Flutter handles calling your painter's paint method when it's time to draw. The widget is the frame; the painter is the artwork.

HOW IT WORKS You subclass CustomPainter and must implement two key methods. First, paint(Canvas canvas, Size size), which is where all drawing logic lives. You use the provided canvas object to call drawing commands like drawRect, drawCircle, or drawPath. Second, shouldRepaint(CustomPainter oldDelegate), a crucial performance method. It should return true only if the new painter has different properties than the old one, warranting a redraw. For animations, pass a Listenable to your painter's constructor to trigger repaints efficiently without rebuilding the widget tree.

WHEN TO USE IT Use CustomPaint for performance-sensitive custom graphics. It's perfect for static decorations, dynamic data visualizations like bar charts or pie charts, or interactive elements like a color wheel where you need pixel-level control over the appearance. It's your tool when composing existing widgets is too slow or too complex.

WHEN NOT TO USE IT Don't use CustomPaint for tasks that can be achieved by composing existing widgets. It's more complex and less declarative than the standard widget approach. Avoid it for simple layouts or standard UI elements like buttons and text fields; use Container, Row, and Column for those.

ONE CANONICAL EXAMPLE A common use is creating a background effect. To draw a sky with a sun, you'd create a Sky class extending CustomPainter. In its paint method, you'd define a RadialGradient for the sun and draw a Rect filled with that gradient onto the canvas. Since the sky is static, its shouldRepaint method would simply return false to prevent unnecessary redraws.

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.