horizontal_dashed_line.dart 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import 'package:flutter/material.dart';
  2. class HorizontalDashedLine extends StatelessWidget {
  3. final double width; // 总宽度
  4. final Color color; // 颜色
  5. final double strokeWidth; // 线条粗细
  6. final double dashLength; // 每段虚线长度
  7. final double dashSpace; // 间隔长度
  8. const HorizontalDashedLine({
  9. this.width = 100,
  10. this.color = Colors.grey,
  11. this.strokeWidth = 1,
  12. this.dashLength = 5,
  13. this.dashSpace = 3,
  14. super.key,
  15. });
  16. @override
  17. Widget build(BuildContext context) {
  18. return CustomPaint(
  19. size: Size(width, strokeWidth), // 高度设为 strokeWidth,宽度根据传参变化
  20. painter: _HorizontalDashedLinePainter(
  21. color: color,
  22. strokeWidth: strokeWidth,
  23. dashLength: dashLength,
  24. dashSpace: dashSpace,
  25. ),
  26. );
  27. }
  28. }
  29. class _HorizontalDashedLinePainter extends CustomPainter {
  30. final Color color;
  31. final double strokeWidth;
  32. final double dashLength;
  33. final double dashSpace;
  34. _HorizontalDashedLinePainter({
  35. required this.color,
  36. required this.strokeWidth,
  37. required this.dashLength,
  38. required this.dashSpace,
  39. });
  40. @override
  41. void paint(Canvas canvas, Size size) {
  42. final paint = Paint()
  43. ..color = color
  44. ..strokeWidth = strokeWidth
  45. ..style = PaintingStyle.stroke;
  46. double startX = 0;
  47. double centerY = size.height / 2; // 让虚线在垂直方向居中
  48. while (startX < size.width) {
  49. canvas.drawLine(
  50. Offset(startX, centerY),
  51. Offset(startX + dashLength, centerY),
  52. paint,
  53. );
  54. startX += dashLength + dashSpace;
  55. }
  56. }
  57. @override
  58. bool shouldRepaint(covariant _HorizontalDashedLinePainter oldDelegate) {
  59. return oldDelegate.color != color ||
  60. oldDelegate.strokeWidth != strokeWidth ||
  61. oldDelegate.dashLength != dashLength ||
  62. oldDelegate.dashSpace != dashSpace;
  63. }
  64. }