The Canvas API: Paths, Paints, and Shaders
Draw shapes, gradients, and strokes using Canvas primitives and the Paint configuration.
Meet the Canvas
When you build a CustomPainter, Flutter hands you two things in paint(): a Canvas and a Size.
- Canvas is your drawing surface. It exposes primitives like
drawRect,drawCircle,drawPath, anddrawLine. - Size tells you how big the area is, so you can scale your drawing to fit any device.
Every draw call needs a Paint object that describes how to draw: color, stroke vs fill, width, and more.
void paint(Canvas canvas, Size size) {
final paint = Paint()..color = const Color(0xFF2196F3);
canvas.drawRect(
Rect.fromLTWH(0, 0, size.width, size.height),
paint,
);
}The Paint Object
A Paint is a bundle of styling options. The most important fields are:
color— the color used to draw.style—PaintingStyle.fill(solid interior) orPaintingStyle.stroke(outline only).strokeWidth— line thickness when stroking.isAntiAlias— smooth edges, on by default.
Flutter idiom uses the cascade operator .. to configure a freshly created Paint in one expression.
final fill = Paint()
..color = const Color(0xFFE91E63)
..style = PaintingStyle.fill;
final outline = Paint()
..color = const Color(0xFF000000)
..style = PaintingStyle.stroke
..strokeWidth = 4.0;All lessons in this course
- The Canvas API: Paths, Paints, and Shaders
- Building an Interactive Custom Chart Widget
- Clipping, Blend Modes, and Layer Compositing
- Hit Testing and Repaint Optimization