Sub topic 1
How CustomPaint and CustomPainter Fit Together
Prerequisites
You should be comfortable with Dart classes and inheritance, and you should have built simple widget trees with StatelessWidget. You do not need prior experience with drawing APIs.
The two widgets
CustomPaint is a widget that reserves a rectangular area on screen. It does not know how to draw anything. You give it a CustomPainter, a class you write that overrides paint. Flutter calls paint whenever the area needs to be drawn, and it passes in a Canvas and the Size of the area.
Coordinates and sizing
The origin (0, 0) is the top-left corner. X increases to the right, and Y increases downward. Read the size argument instead of hard-coding pixel values, so your drawing fits whatever space the parent layout gives it.
Canvas and Paint
Canvas is the surface you draw on. It has methods such as drawRect, drawCircle, drawLine, and drawArc. Paint holds the look of a shape: its color, whether it is filled or stroked, and the stroke width.
Drawing lines, rectangles, circles, and arcs
import 'dart:math' as math;
import 'package:flutter/material.dart';
class ShapesPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final fill = Paint()..color = Colors.teal;
canvas.drawRect(Offset.zero & size, fill);
canvas.drawCircle(
size.center(Offset.zero),
size.shortestSide / 3,
Paint()..color = Colors.white,
);
canvas.drawLine(
Offset.zero,
Offset(size.width, size.height),
Paint()
..color = Colors.black
..strokeWidth = 2,
);
canvas.drawArc(
Rect.fromLTWH(10, 10, 80, 80),
0,
math.pi,
false,
Paint()
..color = Colors.orange
..style = PaintingStyle.stroke
..strokeWidth = 4,
);
}
@override
bool shouldRepaint(covariant ShapesPainter oldDelegate) => false;
}
// Usage:
// CustomPaint(size: const Size(200, 200), painter: ShapesPainter())drawArc takes a bounding rectangle, a start angle, and a sweep angle, both in radians. An angle of 0 points to the three o'clock position, and positive sweeps run clockwise. The last argument, false, means the arc is not connected to the center.
Exercise
In the arc above, you change the sweep angle from math.pi to 2 * math.pi. What shape appears?
Show answer
A full circle outline in orange, because 2π radians is one complete turn.