flutter 自定义分割线

flutter 自定义分割线

直接上代码,不看注释也能看懂

import 'package:flutter/material.dart';

class DashedDivider extends StatelessWidget {
  final double height; // 分隔线的高度
  final Color color; // 分隔线的颜色
  final double dashWidth; // 虚线的宽度
  final double dashSpace; // 虚线之间的间距
  final double indent; // 左侧缩进的宽度
  final double endIndent; // 右侧缩进的宽度

  DashedDivider({
    this.height = 1.0,
    this.color = Colors.grey,
    this.dashWidth = 5.0,
    this.dashSpace = 3.0,
    this.indent = 0.0,
    this.endIndent = 0.0,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        SizedBox(width: indent), // 左侧缩进
        Expanded(
          child: CustomPaint(
            painter: DashedDividerPainter(
              color: color,
              dashWidth: dashWidth,
              dashSpace: dashSpace,
            ),
            child: SizedBox(
              height: height,
            ),
          ),
        ),
        SizedBox(width: endIndent), // 右侧缩进
      ],
    );
  }
}

class DashedDividerPainter extends CustomPainter {
  final Color color; // 虚线的颜色
  final double dashWidth; // 虚线的宽度
  final double dashSpace; // 虚线之间的间距

  DashedDividerPainter({
    required this.color,
    required this.dashWidth,
    required this.dashSpace,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color // 设置画笔颜色为虚线的颜色
      ..strokeWidth = size.height // 设置画笔宽度为虚线的高度
      ..style = PaintingStyle.stroke; // 设置画笔样式为描边

    final dashCount = (size.width / (dashWidth + dashSpace)).floor(); // 计算虚线的数量

    for (var i = 0; i < dashCount; i++) {
      final startX = i * (dashWidth + dashSpace); // 计算每条虚线的起始横坐标
      canvas.drawLine(
        Offset(startX, 0), // 虚线的起点坐标
        Offset(startX + dashWidth, 0), // 虚线的终点坐标
        paint, // 使用定义的画笔绘制虚线
      );
    }
  }

  @override
  bool shouldRepaint(DashedDividerPainter oldDelegate) {
    //返回true时,会触发paint方法进行重新绘制;当返回false时,不会触发重新绘制
    return oldDelegate.color != color ||
        oldDelegate.dashWidth != dashWidth ||
        oldDelegate.dashSpace != dashSpace;
  }
}

使用

Expanded(child: DashedDivider(
            indent: 10,
            endIndent: 10,
            dashWidth: 4,
            dashSpace: 2,
          )),
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容