How to draw a curved line chart with CustomPainter?

Viewed 439

I'm trying to draw a line graph with some smooth curves, like this one from fl_chart :

enter image description here

I tried using quadraticBezierTo, but it didn't work :

enter image description here

This is my code, is there any other way?

import 'package:flutter/material.dart';

class DrawLines extends StatefulWidget {
  final Coordinates lineCoordinates;
  final double yHeight;

  DrawLines({required this.lineCoordinates, required this.yHeight});

  @override
  _DrawLinesState createState() => _DrawLinesState();
}

class _DrawLinesState extends State<DrawLines> {
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      foregroundPainter: LinePainter(
          coordinates: widget.lineCoordinates, yHeight: widget.yHeight),
    );
  }
}

class CoordValues {
  late double x;
  late double y;

  CoordValues({required this.x, required this.y});
}

class Coordinates {
  late CoordValues startCoords;
  late CoordValues endCoords;

  Coordinates({required this.startCoords, required this.endCoords});
}

class LinePainter extends CustomPainter {
  late Coordinates coordinates;
  late double yHeight;

  LinePainter({required this.coordinates, required this.yHeight});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Color(0xFF295AE3)
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 2;

    //curved
    Path path = Path();

    path.moveTo(coordinates.startCoords.x, yHeight - coordinates.startCoords.y);
    path.quadraticBezierTo(
        coordinates.startCoords.x + 15,
        coordinates.startCoords.y,
        coordinates.endCoords.x + 15,
        yHeight - coordinates.endCoords.y);
    //for every two points one line is drawn

  

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

I think my question is pretty straightforward but somehow stackoverflow wants me to write more.

0 Answers
Related