A simple guide for learning to use the CustomPaint
widget
If you haven’t seen it already, you might want to start by watching the Flutter Widget of the Week video about CustomPaint. I’ll be showing how to do many of the things in that video.
Setup
Create a new project and replace main.dart with the following code:
Notes:
- To paint in Flutter you use the
CustomPaint
widget. If you don’t give it a child, you should set the size. Here I made the size300 x 300
logical pixels. (If you do give it a child widget, then CustomPaint will take its size. Thepainter
will paint below the child widget andforegroundPainter
will paint on top of the child widget.) - The
CustomPaint
widget takes aCustomPainter
object (note the “-er” ending) as a parameter. TheCustomPainter
gives you a canvas that you can paint on. - The
CustomPainter
subclass overrides two methods:paint()
andshouldRepaint()
. - You will do your custom painting in
paint()
. For all of my examples below, insert the code here. shouldRepaint()
is called when theCustomPainter
is rebuilt. If you returnfalse
then the framework will use the previous result of paint (thus saving work). But if you returntrue
thenpaint()
will get called again. You could do something like check ifoldPainter.someParameter != someParameter
to make the decision. But we don’t have changing parameters today so we will returnfalse
.
Points
Add the following import:
import 'dart:ui' as ui;
Replace MyPainter.paint()
with the following code:
@override
void paint(Canvas canvas, Size size) {
final pointMode = ui.PointMode.points;
final points = [
Offset(50, 100),
Offset(150, 75)…