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) {
  // Use theme padding
  final leftPadding = theme.padding.left;
  final rightPadding = theme.padding.right;
  final topPadding = theme.padding.top;
  final bottomPadding = theme.padding.bottom;

  final chartSize = Size(
    size.width - leftPadding - rightPadding,
    size.height - topPadding - bottomPadding,
  );
  final chartOffset = Offset(leftPadding, topPadding);

  if (dataSets.isEmpty) return;

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

  for (final dataSet in dataSets) {
    final point = dataSet.dataPoint;
    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;
  // Add extra padding to account for point radius
  final maxYAdjusted = maxY > 0 ? maxY * 1.2 : 1.0; // Increased from 1.15 to 1.2

  // Add padding for X axis to prevent points from being cut off
  // Calculate padding that accounts for point radius (max 6.5px) and glow (max 10px)
  final xRange = maxX - minX;
  final maxPointRadius = 10.0; // Maximum radius including glow
  final xPaddingInPixels = maxPointRadius;

  // Convert pixel padding to data units
  // If chartSize.width is available, convert pixels to data range
  final xPadding = (xRange > 0 && xRange.isFinite && chartSize.width > 0)
      ? (xPaddingInPixels / chartSize.width) * xRange
      : (xRange > 0 && xRange.isFinite) ? xRange * 0.08 : 0.0; // Fallback to 8% if width not available

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

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

  // Clip to chart bounds to prevent lines/areas from extending outside
  canvas.clipRect(Rect.fromLTWH(0, 0, chartSize.width, chartSize.height));

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

  // Group datasets by color to draw lines
  final Map<Color, List<ChartDataPoint>> colorGroups = {};
  for (final dataSet in dataSets) {
    if (!colorGroups.containsKey(dataSet.color)) {
      colorGroups[dataSet.color] = [];
    }
    colorGroups[dataSet.color]!.add(dataSet.dataPoint);
  }

  // Draw each color group as a separate line
  for (final entry in colorGroups.entries) {
    final color = entry.key;
    final pointsList = entry.value;

    if (pointsList.isEmpty) continue;

    // Sort points by x coordinate for proper line drawing
    pointsList.sort((a, b) => a.x.compareTo(b.x));

    final points = pointsList
        .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: [
            color.withValues(alpha: 0.4 * animationProgress),
            color.withValues(alpha: 0.15 * animationProgress),
            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 = 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 = 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;

        // Find the dataset index for this color group
        final datasetIndex = dataSets.indexWhere((ds) => ds.color == color);
        final isSelected = selectedPoint != null &&
            selectedPoint!.isHit &&
            selectedPoint!.datasetIndex == datasetIndex &&
            selectedPoint!.elementIndex == i;

        final isHovered = hoveredPoint != null &&
            hoveredPoint!.isHit &&
            hoveredPoint!.datasetIndex == datasetIndex &&
            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 =
              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 = 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,
    dataSets: dataSets,
  );
  canvas.restore();
}