Back to results for “Performance & Optimization”
Flutter › Custom Painters & CustomPaint

Why is properly implementing the shouldRepaint method on a CustomPainter important for performance, and what happens if it always incorrectly returns true?

Intermediate

Answer

The shouldRepaint method tells Flutter whether the custom painter actually needs to redraw itself again whenever its associated widget rebuilds, and correctly implementing it by comparing the old painter's relevant properties against the new painter's properties, only returning true when something that actually affects the visual output has genuinely changed, avoids unnecessary and potentially expensive repainting operations, whereas always returning true unconditionally means the potentially expensive paint method runs on every single rebuild regardless of whether anything visually relevant actually changed, which can noticeably hurt performance for a complex custom drawing.
@override
bool shouldRepaint(covariant MyChartPainter oldDelegate) {
  return oldDelegate.dataPoints != dataPoints;
}
Real-world example A custom chart painter compares its old and new data points within shouldRepaint, correctly avoiding an unnecessary and computationally expensive redraw whenever a parent widget rebuilds for a completely unrelated reason that does not actually affect the chart's underlying data.

Common follow-ups: How expensive is it typically to actually compare complex objects within shouldRepaint?;What happens visually if shouldRepaint incorrectly returns false when it actually should return true?