import 'package:flutter/material.dart'; class HorizontalDashedLine extends StatelessWidget { final double width; // 总宽度 final Color color; // 颜色 final double strokeWidth; // 线条粗细 final double dashLength; // 每段虚线长度 final double dashSpace; // 间隔长度 const HorizontalDashedLine({ this.width = 100, this.color = Colors.grey, this.strokeWidth = 1, this.dashLength = 5, this.dashSpace = 3, super.key, }); @override Widget build(BuildContext context) { return CustomPaint( size: Size(width, strokeWidth), // 高度设为 strokeWidth,宽度根据传参变化 painter: _HorizontalDashedLinePainter( color: color, strokeWidth: strokeWidth, dashLength: dashLength, dashSpace: dashSpace, ), ); } } class _HorizontalDashedLinePainter extends CustomPainter { final Color color; final double strokeWidth; final double dashLength; final double dashSpace; _HorizontalDashedLinePainter({ required this.color, required this.strokeWidth, required this.dashLength, required this.dashSpace, }); @override void paint(Canvas canvas, Size size) { final paint = Paint() ..color = color ..strokeWidth = strokeWidth ..style = PaintingStyle.stroke; double startX = 0; double centerY = size.height / 2; // 让虚线在垂直方向居中 while (startX < size.width) { canvas.drawLine( Offset(startX, centerY), Offset(startX + dashLength, centerY), paint, ); startX += dashLength + dashSpace; } } @override bool shouldRepaint(covariant _HorizontalDashedLinePainter oldDelegate) { return oldDelegate.color != color || oldDelegate.strokeWidth != strokeWidth || oldDelegate.dashLength != dashLength || oldDelegate.dashSpace != dashSpace; } }