Flutter中不使用外部包实现两个Container间的虚线分隔线
Flutter 实现两个Container之间的虚线分隔线
Flutter自带的Divider组件确实不支持虚线样式,你可以用以下两种方法实现需求:
方法一:使用Container + BoxDecoration(简单快捷)
这种方式利用容器边框的虚线样式实现,代码简洁,适配基础场景:
Container( height: 1, // 对应原Divider的indent和endIndent margin: const EdgeInsets.symmetric(horizontal: 1), decoration: BoxDecoration( border: Border( bottom: BorderSide( color: Colors.grey.shade200, width: 1, // 对应原Divider的thickness style: BorderStyle.dashed, // 设置为虚线 ), ), ), )
方法二:自定义CustomPaint(灵活可控)
如果需要精细调整虚线的长度、间距等细节,可通过自定义绘制实现:
1. 定义虚线绘制器
class DashedLinePainter extends CustomPainter { final Color color; final double strokeWidth; final double dashLength; final double dashSpace; DashedLinePainter({ required this.color, this.strokeWidth = 1, this.dashLength = 5, this.dashSpace = 3, }); @override void paint(Canvas canvas, Size size) { final paint = Paint() ..color = color ..strokeWidth = strokeWidth ..style = PaintingStyle.stroke; double currentX = 0; while (currentX < size.width) { canvas.drawLine( Offset(currentX, 0), Offset(currentX + dashLength, 0), paint, ); currentX += dashLength + dashSpace; } } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return oldDelegate != this; } }
2. 使用自定义绘制组件
CustomPaint( size: const Size(double.infinity, 1), // 宽度自适应父容器,高度为1 painter: DashedLinePainter( color: Colors.grey.shade200, strokeWidth: 1, // 可按需调整dashLength和dashSpace参数 ), )
内容的提问来源于stack exchange,提问作者Naimish Patel
相关产品推荐
相关产品推荐

