Flutter – How to draw dashed line on Canvas

Today, I have a task to create a bar chart with horizontal dashed lines on it. So far I haven’t tried to draw dashed lines on Canvas in Flutter. After making some search, I found that Flutter does not support dashed line, we have to do it manually.

In this post, I save my approach here as a reference for myself and other people who need it later.

1. Add CustomPaint as a child of your widget

class YourWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      // Change to your preferred size.
      // Width and height will be used under "paint" method below. 
      // The canvas accesses it by using size.width, size.height
      height: 300,
      width: 300,
      child: CustomPaint(
        painter: YourCustomPaint(),
      ),
    );
  }
}

2. Custom your paint

class YourCustomPaint extends CustomPainter {

  @override
  void paint(Canvas canvas, Size size) {
    final Paint paint = Paint();
    ..color = Colors.red
    ..strokeCap = StrokeCap.square
    ..strokeWidth = 1;

    _drawDashedLine(canvas, paint, size);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }

  void _drawDashedLine(Canvas canvas, Size size, Paint paint) {
    // Chage to your preferred size
    const int dashWidth = 4;
    const int dashSpace = 4;

    // Start to draw from left size. 
    // Of course, you can change it to match your requirement.
    double startX = 0;
    double y = 10;

    // Repeat drawing until we reach the right edge.
    // In our example, size.with = 300 (from the SizedBox)
    while (startX < size.width) {
      // Draw a small line.
      canvas.drawLine(Offset(startX, y), Offset(startX + dashWidth, y), paint);
      
      // Update the starting X
      startX += dashWidth + dashSpace;
    }
  }
}

If you are looking for mobile/web Software Engineers to build you next projects, please Contact Nextfunc team here!

Tagged : / / / / /
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x