CodeBlanks Logo Icon CodeBlanks

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;

Practice 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.

Starter code

main.dart
import 'package:flutter/material.dart';

// MyPainter sınıfını tanımla

void main() {
  // shouldRepaint sonucunu yazdır
}

Sample solution

main.dart
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));
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which two parameters does the paint method signature have?

  • Color and Offset
  • BuildContext and Widget
  • Paint and Path
  • Canvas and Size Correct answer

Explanation: The paint method signature is void paint(Canvas canvas, Size size); you draw on the canvas, and size gives the drawing area.

2 Override the paint method

Question
class MyPainter extends CustomPainter {
  @override
  void ____(Canvas canvas, Size size) {}

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
Answer
class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {}

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

Explanation: The paint method is where CustomPainter does the drawing; its signature must be void paint(Canvas canvas, Size size).

3 CustomPainter parts

Term Meaning
CustomPainter Abstract painting class
paint Method that draws
shouldRepaint Repaint decision
Canvas Drawing surface

All lessons in Advanced