import 'package:flutter/material.dart';


class RichText1 extends StatefulWidget {
  String content = '';
  RichText1({Key key,this.content}) : super(key: key);

  @override
  State<RichText1> createState() => _RichTextState();
}

class _RichTextState extends State<RichText1> {
  // 全文、收起 的状态
  bool mIsExpansion = false;

  // 最大显示行数
  int mMaxLine = 5;

  @override
  Widget build(BuildContext context) {
    return Container(
      child:_RichText(widget.content) ,
    );
  }

  ///[_text ] 传入的字符串
  Widget _RichText(String _text) {
    if (IsExpansion(_text)) {
      //是否截断
      if (mIsExpansion) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              _text,
              textAlign: TextAlign.left,
            ),
            Container(
              child: InkWell(
                onTap: (){_isShowText();},
                child: Row(mainAxisAlignment:MainAxisAlignment.end ,children: [ Text('收起',style: TextStyle(color: Colors.grey))],),
              ),
            )
          ],
        );
      } else {
        return Column(
          children: <Widget>[
            Text(
              _text,
              maxLines: 3,
              textAlign: TextAlign.left,
              overflow: TextOverflow.ellipsis,
            ),
            Container(
              child: InkWell(
                onTap: (){_isShowText();},
                child: Row(mainAxisAlignment:MainAxisAlignment.end ,children: [ Text('全文',style: TextStyle(color: Colors.grey))],),
              ),
            )
          ],
        );
      }
    } else {
      return Text(
        _text,
        maxLines: 3,
        textAlign: TextAlign.left,
        overflow: TextOverflow.ellipsis,
      );
    }
  }

  bool IsExpansion(String text) {
    TextPainter _textPainter = TextPainter(
        maxLines: 3,
        text: TextSpan(
            text: text, style: const TextStyle(fontSize: 16.0, color: Colors.black)),
        textDirection: TextDirection.ltr)..layout(maxWidth: 90, minWidth: 50);
    // if (_textPainter.didExceedMaxLines) {//判断 文本是否需要截断
      if (text.length > 65) {//判断 文本是否需要截断
          return true;
        } else {
          return false;
        }
  }

  void _isShowText() {
    if (mIsExpansion) {
      //关闭
      setState(() {
        mIsExpansion = false;
      });
    } else {
      //打开
      setState(() {
        mIsExpansion = true;
      });
    }
  }
}

