How to Add a Dashed line in Flutter? (Free Code)

Sometimes we need to make dashed lines for our flutter App (adding a ticket-like view) where we have to add some dashed lines to show tickets and there may be lots of other regions too.


CustomPainter

So to add dashed/dotted line in flutter we need to make a new class with CustomPainter Class. (Documentation). CoustomPainter Allows you to add custom Shapes in the flutter app. With the help of Different Drawing functions, we can make different Shapes. here is the link to the video made by the flutter team (VIDEO LINK). Adding logic and maths equations to make a share is Difficult for those who don’t like maths.

Truth

Adding logic and maths equations to make a share is Difficult for those who don’t like maths.

So Rather than opening maths books again, I have a code that will make your job done of making a Dashed line in Flutter.


Easy Code To implement

I am giving you easy Steps and code to implement dashed lines in a flutter.

Step1

Create a New file named DashedLinePainter and add the following code.

import 'package:flutter/material.dart';

class DashedLinePainter extends CustomPainter {
 
 @override
  void paint(Canvas canvas, Size size) {
    double dashWidth = 9, dashSpace = 5, startX = 0;
    final paint = Paint()
      ..color = //color
      ..strokeWidth = 1;
    while (startX < size.width) {
      canvas.drawLine(Offset(startX, 0), Offset(startX + dashWidth, 0), paint);
      startX += dashWidth + dashSpace;
    }
  }
  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;

}

Step 2

On line 8 where it Says //color add the colors of your dashes (eg. Colors.grey). And you can also play with StrokeWidth.

Step 3

Now Import the DashedLinePainter class and add the following code where you want to show those dashed lines in your flutter app.

CustomPaint(painter: DashedLinePainter()),

In the previous line, we are calling CustomPaint Function and passing our painter class which we made DashedLinePainter().


So here’s how we can make a Dashed line in Flutter. If you like this post useful make sure to save it and share it with others. If you guys having a problem then let me know in the comments I will solve it.

For more Flutter tutorials, Tips, Tricks, Free code, Questions, and Error Solving.

Remember FlutterDecode.com

3 thoughts on “How to Add a Dashed line in Flutter? (Free Code)”

Leave a Comment