import 'dart:ui';

import 'package:flutter/material.dart';

class DashedBorderPainter extends CustomPainter {
  final double dashWidth;
  final double dashSpace;
  final Color color;

  DashedBorderPainter({
    this.dashWidth = 4.0,
    this.dashSpace = 2.0,
    this.color = Colors.black,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = 0.5
      ..style = PaintingStyle.stroke;

    final Path topPath = Path()
      ..moveTo(0, 0)
      ..lineTo(size.width, 0);

    final Path bottomPath = Path()
      ..moveTo(0, size.height)
      ..lineTo(size.width, size.height);

    final dashedTopPath = _createDashedPath(topPath, dashWidth, dashSpace);
    final dashedBottomPath = _createDashedPath(bottomPath, dashWidth, dashSpace);

    canvas.drawPath(dashedTopPath, paint);
    canvas.drawPath(dashedBottomPath, paint);
  }

  Path _createDashedPath(Path source, double dashWidth, double dashSpace) {
    final Path dashedPath = Path();
    for (PathMetric pathMetric in source.computeMetrics()) {
      double distance = 0.0;
      while (distance < pathMetric.length) {
        final double nextDistance = distance + dashWidth;
        dashedPath.addPath(
          pathMetric.extractPath(distance, nextDistance),
          Offset.zero,
        );
        distance = nextDistance + dashSpace;
      }
    }
    return dashedPath;
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
