You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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:

  1. 在pubspec.yaml中添加依赖:
dependencies:
  flutter_dash: ^0.0.1 # 请检查最新版本
  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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 21:01:54