While Flutter's standard widget library provides versatile UI primitives, custom financial charts, waveforms, and bezier progress paths require raw access to the Skia/Impeller canvas.
CustomPainter provides low-level drawing capabilities while maintaining tight integration with Flutter's animation engine.
1. The Anatomy of a CustomPainter
dart
class SmoothWaveformPainter extends CustomPainter {
final List<double> amplitudes;
final double animationProgress;
final Color primaryColor;
SmoothWaveformPainter({
required this.amplitudes,
required this.animationProgress,
required this.primaryColor,
});
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = primaryColor
..strokeWidth = 3.0
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round;
final path = Path();
final stepX = size.width / (amplitudes.length - 1);
for (int i = 0; i < amplitudes.length; i++) {
final x = i * stepX;
final y = (size.height / 2) + (amplitudes[i] * (size.height / 2) * sin(animationProgress * 2 * pi));
if (i == 0) {
path.moveTo(x, y);
} else {
path.lineTo(x, y);
}
}
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(covariant SmoothWaveformPainter oldDelegate) {
return oldDelegate.animationProgress != animationProgress ||
oldDelegate.amplitudes != amplitudes;
}
}2. Performance Rule: shouldRepaint Precision
Always implement shouldRepaint with precise inequality comparisons. Returning true unconditionally triggers unnecessary rasterization and drains device battery life.
