How to Create Horizontal Dash/Dotted Line in Flutter App

If you are getting difficulties drawing horizontal dash/dotted line with Flutter then see the example below and apply a similar class to your project. the output of the following Dart code looks like:

Use the following Dart code in your project.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Home());
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Horizontal Dotted/Dash Line"), //appbar title
          backgroundColor: Colors.redAccent, //appbar color
        ),
        body: Container(
           color: Colors.white,
            height: 150.0, //height of container
            child: Center(
              child:CustomPaint(painter: DrawDottedhorizontalline()),
              //drawing horizontal dotted/dash line          
            ),
        ),
    );
  }
}

class DrawDottedhorizontalline extends CustomPainter {
  Paint _paint;
  DrawDottedhorizontalline() {
    _paint = Paint();
    _paint.color = Colors.black; //dots color
    _paint.strokeWidth = 2; //dots thickness
    _paint.strokeCap = StrokeCap.square; //dots corner edges
  }

  @override
  void paint(Canvas canvas, Size size) {
    for (double i = -300; i < 300; i = i + 15) {
      // 15 is space between dots
      if (i % 3 == 0)
        canvas.drawLine(Offset(i, 0.0), Offset(i + 10, 0.0), _paint);
    }
  }

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

Output:

Read the inline comment on code to understand better.

No any Comments on this Article


Please Wait...