import 'package:flutter/material.dart';

class DashedLineText extends StatelessWidget {
  final String text;
  final TextStyle? textStyle;
  final Color lineColor;
  final double strokeWidth;
  final double dashLength;

  const DashedLineText({
    super.key,
    required this.text,
    this.textStyle,
    this.lineColor = Colors.blue,
    this.strokeWidth = 1.0,
    this.dashLength = 3.0,
  });

  @override
  Widget build(BuildContext context) {
    return Row(

      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Expanded(
          child: CustomPaint(
            painter: _DashedLinePainter(
              color: lineColor,
              strokeWidth: strokeWidth,
              dashLength: dashLength,
            ),
            size: const Size(double.infinity, 1),
          ),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8),
          child: Text(
            text,
            style: textStyle ?? Theme.of(context).textTheme.bodyMedium,
          ),
        ),
        Expanded(
          child: CustomPaint(
            painter: _DashedLinePainter(
              color: lineColor,
              strokeWidth: strokeWidth,
              dashLength: dashLength,
            ),
            size: const Size(double.infinity, 1),
          ),
        ),
      ],
    );
  }
}

class _DashedLinePainter extends CustomPainter {
  final Color color;
  final double strokeWidth;
  final double dashLength;

  const _DashedLinePainter({
    required this.color,
    required this.strokeWidth,
    required this.dashLength,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke;

    double startX = 0;
    while (startX < size.width) {
      canvas.drawLine(
        Offset(startX, size.height / 2),
        Offset(startX + dashLength, size.height / 2),
        paint,
      );
      startX += dashLength * 2; // 间隔 = 线段长度 + 空白长度
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}