Sub topic 2
Fill, stroke, caps, and joins
This chapter assumes you can write a CustomPainter with a paint method, that you know Size, and that you have used an AnimationController.
Fill and stroke
A Paint object sets how a shape is drawn. In PaintingStyle.fill mode, the shape's interior is colored. In PaintingStyle.stroke mode, only the outline is drawn, using strokeWidth.
Caps and joins
strokeCap controls the ends of an open line. strokeJoin controls the corners where two segments meet. Use StrokeCap.round and StrokeJoin.round for soft, rounded corners.
import 'package:flutter/material.dart';
class TrianglePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final fill = Paint()
..color = Colors.teal
..style = PaintingStyle.fill;
final stroke = Paint()
..color = Colors.indigo
..style = PaintingStyle.stroke
..strokeWidth = 8
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round;
final path = Path()
..moveTo(20, size.height - 20)
..lineTo(size.width / 2, 20)
..lineTo(size.width - 20, size.height - 20)
..close();
canvas.drawPath(path, fill);
canvas.drawPath(path, stroke);
}
@override
bool shouldRepaint(covariant TrianglePainter oldDelegate) => false;
}Building shapes with Path
A Path is a sequence of segments. moveTo starts a new subpath, lineTo adds a straight segment, and close joins the last point to the first. addArc adds a curved segment along an oval's edge. Draw the finished path once with canvas.drawPath.
Deciding when to repaint with shouldRepaint
Flutter calls shouldRepaint when a new painter replaces the old one. Return true only when the new painter's data changed. Compare the fields that affect the drawing.
@override
bool shouldRepaint(covariant ProgressPainter oldDelegate) =>
oldDelegate.progress != progress;Callout note: Returning true always is safe but wasteful, because every rebuild repaints the canvas.
Animating a painter with the repaint listenable
Pass an Animation to the super(repaint: ...) constructor. The painter then repaints on every animation tick without rebuilding the widget tree. Keep the controller in a StatefulWidget and dispose it in dispose.
Exercise: Q: Why should a painter that uses repaint: return false from shouldRepaint when its only changing input is the animation? A: The animation already triggers repaints through the repaint listenable, so shouldRepaint does not need to report a change for each tick.