如何在Flutter中实现如图所示的虚线效果?
如何在Flutter中实现水平虚线样式
方法一:使用CustomPaint原生实现
通过自定义CustomPainter可以完全控制虚线的样式,适合需要高度定制的场景:
首先定义虚线绘制器:
class DashedLinePainter extends CustomPainter { final Color color; final double strokeWidth; final double dashLength; final double dashSpace; DashedLinePainter({ this.color = Colors.grey, this.strokeWidth = 1.0, this.dashLength = 5.0, this.dashSpace = 3.0, }); @override void paint(Canvas canvas, Size size) { final paint = Paint() ..color = color ..strokeWidth = strokeWidth ..style = PaintingStyle.stroke; double currentPos = 0; while (currentPos < size.width) { canvas.drawLine( Offset(currentPos, size.height / 2), Offset(currentPos + dashLength, size.height / 2), paint, ); currentPos += dashLength + dashSpace; } } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return oldDelegate != this; } }
在Widget中使用:
CustomPaint( size: const Size(double.infinity, 1), painter: DashedLinePainter( color: Colors.grey.shade300, strokeWidth: 1, dashLength: 6, dashSpace: 4, ), )
方法二:使用第三方包快速实现
如果不想自己写绘制逻辑,可以用成熟的第三方包,比如flutter_dash:
- 在
pubspec.yaml中添加依赖:
dependencies: flutter_dash: ^0.0.1 # 请检查最新版本
- 直接使用组件:
FlutterDash( direction: Axis.horizontal, length: double.infinity, dashLength: 6, dashColor: Colors.grey.shade300, dashThickness: 1, dashGapLength: 4, )
垂直虚线适配
如果需要垂直虚线,只需调整CustomPaint的size和绘制逻辑中的坐标,或者修改flutter_dash的direction为Axis.vertical即可。
内容的提问来源于stack exchange,提问作者Huy Nguyen
相关产品推荐
相关产品推荐

