Friday, February 5, 2021

Flutter: Making dashed line matching width of screen

 How can we make dashed line in flutter?

Dart does not have support for this yet. We need to make custom widget for showing dashed line. Code is given below.

class LinePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var max = size.width;
debugPrint("LinePainter max=$max");
var dashWidth = 5.0;
var dashSpace = 5.0;
double startX = 0;
final paint = Paint()..color = Colors.grey;
while (max >= 0) {
canvas.drawLine(Offset(startX, 0), Offset(startX + dashWidth, 0),
        paint..strokeWidth = 1);

final space = (dashSpace + dashWidth);
startX += space;
max -= space.toInt();
}
}

@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
Above code will paint a line of width = size.width.

To use this painter as widget, we have to use 
CustomPaint(painter: LinePainter(),size:Size(400,1))
It will draw a dashed line with 400px width. But we want to draw line 
covering entire width of screen. For that we will use constraint in a container.
Container(constraints: BoxConstraints.tightForFinite(height: 1.0),
    child: CustomPaint(painter: LinePainter(),),)

It will draw a line as shown below

No need to use any external library for showing dashed line.


No comments:

Post a Comment

Android aar deployment in Maven - 2022

Introduction If you are working on android library project, you might be wondering how to publish it on Maven like this . Earl...