Flutter
CustomPainter
Learn paint and shouldRepaint with CustomPainter.
The CustomPainter class
CustomPainter is the abstract class that does the drawing; you must override two methods. The paint method does the actual drawing, and shouldRepaint decides whether to redraw. The CustomPaint widget expects an instance of this class.
class LinePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// drawing here
}
@override
bool shouldRepaint(covariant CustomPainter old) => false;
}
When shouldRepaint should return true
If shouldRepaint returns true, paint is called again. Returning false for a fixed drawing protects performance. If the drawing depends on state, you can compare old and new state and return true.
@override
bool shouldRepaint(covariant CustomPainter old) =>
this.color != (old as MyPainter).color;
Exercise A painter that always returns true
Define MyPainter; leave paint empty, and have shouldRepaint always return true. In main, take an instance and print its shouldRepaint result.
Show example solution
import 'package:flutter/material.dart';
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
void main() {
final painter = MyPainter();
print(painter.shouldRepaint(painter));
}
Test yourself
-
Which two parameters does the paint method signature have?
- Color and Offset
- BuildContext and Widget
- Paint and Path
- Canvas and Size
Show answer
Canvas and Size — The paint method signature is void paint(Canvas canvas, Size size); you draw on the canvas, and size gives the drawing area.
-
Override the paint method
class MyPainter extends CustomPainter {
@override
void ____(Canvas canvas, Size size) {}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
Show answer
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
-
CustomPainter parts
- CustomPainter
- Abstract painting class
- paint
- Method that draws
- shouldRepaint
- Repaint decision
- Canvas
- Drawing surface
Next lesson: Canvas and Paint