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;
    }
  }
}

Tagged : / / / / /
Subscribe
Notify of
guest

3 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Kevin
Kevin
1 year ago

A more general version for any straight line from point p1 to p2:

void _drawDashedLine(Canvas canvas, Offset p1, Offset p2, Paint paint) {
const int dashWidth = 4;
const int dashSpace = 4;

// Get normalized distance vector
var dx = p2.dx - p1.dx;
var dy = p2.dy - p1.dy;
final magnitude = sqrt(dx * dx + dy * dy);
final steps = magnitude ~/ (dashWidth + dashSpace);
dx = dx / magnitude;
dy = dy / magnitude;
var startX = p1.dx;
var startY = p1.dy;

for (int i = 0; i < steps; i++) {
canvas.drawLine(Offset(startX, startY), Offset(startX + dx * dashWidth, startY + dy * dashWidth), paint);
startX += dx * (dashWidth + dashSpace);
startY += dy * (dashWidth + dashSpace);
}
}
sandeep
1 year ago

it will help my website.

anom
anom
2 years ago

pure trash

3
0
Would love your thoughts, please comment.x
()
x