How to Paint in Flutter

Suragch
7 min readJul 5, 2019

A simple guide for learning to use the CustomPaint widget

Photo by Steve Johnson

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 size 300 x 300 logical pixels. (If you do give it a child widget, then CustomPaint will take its size. The painter will paint below the child widget and foregroundPainter will paint on top of the child widget.)
  • The CustomPaint widget takes a CustomPainter object (note the “-er” ending) as a parameter. The CustomPainter gives you a canvas that you can paint on.
  • The CustomPainter subclass overrides two methods: paint() and shouldRepaint().
  • You will do your custom painting in paint(). For all of my examples below, insert the code here.
  • shouldRepaint() is called when the CustomPainter is rebuilt. If you return false then the framework will use the previous result of paint (thus saving work). But if you return true then paint() will get called again. You could do something like check if oldPainter.someParameter != someParameter to make the decision. But we don’t have changing parameters today so we will return false.

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)…

--

--