paint method

  1. @override
void paint(
  1. Canvas canvas,
  2. Size size
)
override

Called whenever the object needs to paint. The given Canvas has its coordinate space configured such that the origin is at the top left of the box. The area of the box is the size of the size argument.

Paint operations should remain inside the given area. Graphical operations outside the bounds may be silently ignored, clipped, or not clipped. It may sometimes be difficult to guarantee that a certain operation is inside the bounds (e.g., drawing a rectangle whose size is determined by user inputs). In that case, consider calling Canvas.clipRect at the beginning of paint so everything that follows will be guaranteed to only draw within the clipped area.

Implementations should be wary of correctly pairing any calls to Canvas.save/Canvas.saveLayer and Canvas.restore, otherwise all subsequent painting on this canvas may be affected, with potentially hilarious but confusing results.

To paint text on a Canvas, use a TextPainter.

To paint an image on a Canvas:

  1. Obtain an ImageStream, for example by calling ImageProvider.resolve on an AssetImage or NetworkImage object.

  2. Whenever the ImageStream's underlying ImageInfo object changes (see ImageStream.addListener), create a new instance of your custom paint delegate, giving it the new ImageInfo object.

  3. In your delegate's paint method, call the Canvas.drawImage, Canvas.drawImageRect, or Canvas.drawImageNine methods to paint the ImageInfo.image object, applying the ImageInfo.scale value to obtain the correct rendering size.

Implementation

@override
void paint(Canvas canvas, Size size) {
  const leftPadding = 50.0;
  const rightPadding = 20.0;
  const topPadding = 20.0;
  const bottomPadding = 40.0;
  final chartSize = Size(
    size.width - leftPadding - rightPadding,
    size.height - topPadding - bottomPadding,
  );
  final chartOffset = const Offset(leftPadding, topPadding);

  if (dataSets.isEmpty) return;

  double minX = double.infinity;
  double maxX = double.negativeInfinity;
  double maxY = double.negativeInfinity;

  for (final dataSet in dataSets) {
    for (final point in dataSet.dataPoints) {
      if (point.x < minX) minX = point.x;
      if (point.x > maxX) maxX = point.x;
      if (point.y > maxY) maxY = point.y;
    }
  }

  if (minX == double.infinity ||
      !minX.isFinite ||
      !maxX.isFinite ||
      !maxY.isFinite) {
    return;
  }

  final minY = 0.0;
  final maxYAdjusted = maxY > 0 ? maxY * 1.15 : 1.0;

  final xRange = maxX - minX;
  final xPadding = (xRange > 0 && xRange.isFinite) ? xRange * 0.05 : 0.0;

  if (!chartSize.width.isFinite ||
      !chartSize.height.isFinite ||
      chartSize.width <= 0 ||
      chartSize.height <= 0) {
    return;
  }

  canvas.save();
  canvas.translate(chartOffset.dx, chartOffset.dy);

  drawGrid(canvas, chartSize, minX, maxX, minY, maxYAdjusted);
  drawAxes(canvas, chartSize, minX, maxX, minY, maxYAdjusted);

  for (final dataSet in dataSets) {
    if (dataSet.dataPoints.isEmpty) continue;

    final points = dataSet.dataPoints
        .map((point) {
          return pointToCanvas(
            point,
            chartSize,
            minX - xPadding,
            maxX + xPadding,
            minY,
            maxYAdjusted,
          );
        })
        .where((offset) => offset.dx.isFinite && offset.dy.isFinite)
        .toList();

    if (points.isEmpty) continue;

    // Draw area fill with step pattern
    if (showArea) {
      final areaPath = Path();
      areaPath.moveTo(points.first.dx, chartSize.height);

      final totalPoints = points.length;
      final animatedPoints = (totalPoints * animationProgress).ceil();

      for (int i = 0; i < animatedPoints && i < points.length; i++) {
        final currentPoint = points[i];
        if (!currentPoint.dx.isFinite || !currentPoint.dy.isFinite) continue;

        if (i == 0) {
          areaPath.lineTo(currentPoint.dx, currentPoint.dy);
        } else {
          final prevPoint = points[i - 1];
          if (!prevPoint.dx.isFinite || !prevPoint.dy.isFinite) continue;

          // Step pattern: horizontal then vertical
          // First draw horizontal line to next x position
          areaPath.lineTo(currentPoint.dx, prevPoint.dy);
          // Then draw vertical line to new y position
          areaPath.lineTo(currentPoint.dx, currentPoint.dy);
        }
      }

      if (animatedPoints > 0 && points.isNotEmpty) {
        Offset lastPoint;
        if (animatedPoints == points.length) {
          lastPoint = points.last;
        } else {
          final lerpedPoint = Offset.lerp(
            points[animatedPoints - 1],
            points[math.min(animatedPoints, points.length - 1)],
            animationProgress,
          );
          lastPoint = (lerpedPoint != null &&
                  lerpedPoint.dx.isFinite &&
                  lerpedPoint.dy.isFinite)
              ? lerpedPoint
              : points.last;
        }

        if (lastPoint.dx.isFinite && lastPoint.dy.isFinite) {
          areaPath.lineTo(lastPoint.dx, chartSize.height);
        }
      }
      areaPath.close();

      final areaPaint = Paint()
        ..shader = LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            dataSet.color.withValues(alpha: 0.4 * animationProgress),
            dataSet.color.withValues(alpha: 0.15 * animationProgress),
            dataSet.color.withValues(alpha: 0.0),
          ],
          stops: const [0.0, 0.5, 1.0],
        ).createShader(Rect.fromLTWH(0, 0, chartSize.width, chartSize.height))
        ..style = PaintingStyle.fill;

      canvas.drawPath(areaPath, areaPaint);
    }

    // Draw step line
    final linePath = Path();
    if (points.isNotEmpty &&
        points.first.dx.isFinite &&
        points.first.dy.isFinite) {
      linePath.moveTo(points.first.dx, points.first.dy);
    }

    final totalPoints = points.length;
    final animatedPoints = (totalPoints * animationProgress).ceil();

    for (int i = 1; i < animatedPoints && i < points.length; i++) {
      final prevPoint = points[i - 1];
      final currentPoint = points[i];

      if (!prevPoint.dx.isFinite ||
          !prevPoint.dy.isFinite ||
          !currentPoint.dx.isFinite ||
          !currentPoint.dy.isFinite) {
        continue;
      }

      // Step pattern: horizontal then vertical
      linePath.lineTo(currentPoint.dx, prevPoint.dy);
      linePath.lineTo(currentPoint.dx, currentPoint.dy);
    }

    final linePaint = Paint()
      ..color = dataSet.color
      ..strokeWidth = lineWidth
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 1.0);

    canvas.drawPath(linePath, linePaint);

    final overlayPaint = Paint()
      ..color = dataSet.color.withValues(alpha: 0.6)
      ..strokeWidth = lineWidth * 0.5
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round;

    canvas.drawPath(linePath, overlayPaint);

    // Draw points
    if (showPoints) {
      final totalPoints = points.length;
      final animatedPoints = (totalPoints * animationProgress).ceil();

      for (int i = 0; i < animatedPoints && i < points.length; i++) {
        final point = points[i];

        if (!point.dx.isFinite || !point.dy.isFinite) continue;

        final pointOpacity = i < animatedPoints - 1 ? 1.0 : animationProgress;

        final isSelected = selectedPoint != null &&
            selectedPoint!.isHit &&
            selectedPoint!.datasetIndex == dataSets.indexOf(dataSet) &&
            selectedPoint!.elementIndex == i;

        final isHovered = hoveredPoint != null &&
            hoveredPoint!.isHit &&
            hoveredPoint!.datasetIndex == dataSets.indexOf(dataSet) &&
            hoveredPoint!.elementIndex == i;

        final glowRadius = isSelected ? 10.0 : (isHovered ? 8.0 : 6.0);
        final glowOpacity = isSelected ? 0.4 : (isHovered ? 0.3 : 0.2);
        final glowPaint = Paint()
          ..color =
              dataSet.color.withValues(alpha: glowOpacity * pointOpacity)
          ..style = PaintingStyle.fill;
        canvas.drawCircle(point, glowRadius, glowPaint);

        final pointRadius = isSelected ? 6.5 : (isHovered ? 5.5 : 4.5);
        final pointPaint = Paint()
          ..color = dataSet.color.withValues(alpha: pointOpacity)
          ..style = PaintingStyle.fill;
        canvas.drawCircle(point, pointRadius, pointPaint);

        final highlightPaint = Paint()
          ..color = Colors.white.withValues(alpha: 0.8 * pointOpacity)
          ..style = PaintingStyle.fill;
        canvas.drawCircle(point, 2, highlightPaint);

        final borderWidth = isSelected ? 3.0 : (isHovered ? 2.0 : 1.5);
        final borderPaint = Paint()
          ..color = isSelected ? Colors.white : theme.backgroundColor
          ..style = PaintingStyle.stroke
          ..strokeWidth = borderWidth;
        canvas.drawCircle(point, pointRadius, borderPaint);
      }
    }
  }

  canvas.restore();

  canvas.save();
  canvas.translate(chartOffset.dx, chartOffset.dy);
  drawAxisLabels(
    canvas,
    chartSize,
    minX - xPadding,
    maxX + xPadding,
    minY,
    maxYAdjusted,
  );
  canvas.restore();
}