How to add line dash in Flutter

前端 未结 10 1007
清歌不尽
清歌不尽 2021-02-07 02:54

How to make a line dash in Flutter like this?

10条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-07 03:21

    You should prefer using CustomPainter because it's more performance and suitable for such issues.

    class DashLine extends StatelessWidget {
      const DashLine({
        Key key,
        this.color,
        this.dashWidth,
        this.dashSpace,
        this.strokeWidth,
      }) : super(key: key);
    
      final Color color;
      final double dashWidth;
      final double dashSpace;
      final double strokeWidth;
    
      @override
      Widget build(BuildContext context) {
        return CustomPaint(
          painter: _DashLinePainter(
            color: color,
            dashWidth: dashWidth,
            dashSpace: dashSpace,
            strokeWidth: strokeWidth,
          ),
        );
      }
    }
    
    class _DashLinePainter extends CustomPainter {
      _DashLinePainter({
        Color color,
        double dashWidth,
        double dashSpace,
        double strokeWidth,
      })  : _color = color ?? Colors.red,
            _dashWidth = dashWidth ?? 5.0,
            _dashSpace = dashSpace ?? 5.0,
            _strokeWidth = strokeWidth ?? 1.0;
    
      final Color _color;
      final double _dashWidth;
      final double _dashSpace;
      final double _strokeWidth;
    
      @override
      void paint(Canvas canvas, Size size) {
        final paint = Paint()
          ..color = _color
          ..strokeWidth = _strokeWidth;
    
        var max = size.width;
        var startX = 0.0;
        while (max >= 0) {
          canvas.drawLine(Offset(startX, 0), Offset(startX + _dashWidth, 0), paint);
          final space = (_dashSpace + _dashWidth);
          startX += space;
          max -= space;
        }
      }
    
      @override
      bool shouldRepaint(_DashLinePainter oldDelegate) {
        return _color != oldDelegate._color ||
            _dashWidth != oldDelegate._dashWidth ||
            _dashSpace != oldDelegate._dashSpace ||
            _strokeWidth != oldDelegate._strokeWidth;
      }
    }
    

提交回复
热议问题