Andrea
Andrea

Reputation: 449

Flutter custom painter class

How does shouldRepaint method from custom painter class in flutter works? I've read the documentation but I don't understand how and when to us it.

Upvotes: 3

Views: 2799

Answers (1)

Richard Heap
Richard Heap

Reputation: 51692

It's a way to give the framework a hint whether it needs to call the paint method of your CustomPainter.

Let's say you have a Widget that takes a Color.

class SomeWidget extends StatelessWidget {
  final Color color;

  SomeWidget(this.color);

  @override
  Widget build(BuildContext context) {
    return new CustomPaint(
      painter: new MyPainter(color),
    );
  }
}

This Widget could get rebuilt by the framework multiple times, but as long as the Color passed to the constructor doesn't change, and the CustomPainter doesn't depend on anything else, then there's no point in repainting the CustomPaint. When the color does change, we want to tell the framework that it should call paint.

So the CustomPainter can hint to the framework by returning true iff the color has changed.

class MyPainter extends CustomPainter {
  final Color color;

  MyPainter(this.color);

  @override
  void paint(Canvas canvas, Size size) {
    // this paint function uses color
    // as long as color is the same there's no point painting again
    // so shouldRepaint only returns true if the color has changed
  }

  @override
  bool shouldRepaint(MyPainter oldDelegate) => color != oldDelegate.color;
}

Upvotes: 4

Related Questions