天天看点

Flutter 可以折叠展开的Text控件

作者:知识点君
import 'package:flutter/material.dart';

class ExpandableText extends StatefulWidget {
  final String text;
  final int maxLines;
  final TextStyle style;
  final TextAlign textAlign;

  ExpandableText({
    required this.text,
    this.maxLines = 1,
    this.style = const TextStyle(),
    this.textAlign = TextAlign.start,
  });

  @override
  _ExpandableTextState createState() => _ExpandableTextState();
}

class _ExpandableTextState extends State<ExpandableText> {
  bool isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final TextPainter textPainter = TextPainter(
          text: TextSpan(text: widget.text, style: widget.style),
          maxLines: isExpanded ? null : widget.maxLines,
          textDirection: TextDirection.ltr,
          textScaleFactor: MediaQuery.of(context).textScaleFactor,
        );

        textPainter.layout(maxWidth: constraints.maxWidth);

        return Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              widget.text,
              maxLines:isExpanded ? 1000 : widget.maxLines,
              overflow: TextOverflow.ellipsis,
              textAlign: widget.textAlign,
              style: widget.style,

            ),
            if (!isExpanded && textPainter.didExceedMaxLines)
              GestureDetector(
                onTap: () {
                  setState(() {
                    isExpanded = true;
                  });
                },
                child: Text(
                  'show more',
                  textAlign: widget.textAlign,
                  style: TextStyle(
                    fontSize: widget.style.fontSize,
                    color: Colors.blue,
                    decoration: TextDecoration.underline,
                  ),
                ),
              ),
            if (isExpanded)
              GestureDetector(
                onTap: () {
                  setState(() {
                   isExpanded = false;
                  });
                },
                child: Text(
                  'show less',
                  textAlign: widget.textAlign,
                  style: TextStyle(
                    fontSize: widget.style.fontSize,
                    color: Colors.blue,
                    decoration: TextDecoration.underline,
                  ),
                ),
              ),
          ],
        );
      },
    );
  }
}