rich_text.dart 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import 'package:flutter/gestures.dart';
  2. import 'package:flutter/material.dart';
  3. // ignore: must_be_immutable
  4. class LinkRichText extends StatefulWidget {
  5. double width;
  6. String text;
  7. LinkRichText({Key? key,required this.width,required this.text}) : super(key: key);
  8. @override
  9. State<LinkRichText> createState() => _LinkRichTextState();
  10. }
  11. class _LinkRichTextState extends State<LinkRichText> {
  12. bool mIsExpaned = false;
  13. int mSelectIndex = -1;
  14. bool isExpaned(String text, width) {
  15. TextPainter _textPainter = TextPainter(
  16. maxLines: 2,
  17. text: TextSpan(
  18. text: text, style: TextStyle(fontSize: 14.0, color: Colors.black)),
  19. textDirection: TextDirection.ltr)..layout(
  20. maxWidth: width-180,minWidth: 80
  21. );
  22. if (_textPainter.didExceedMaxLines){
  23. return true;
  24. }
  25. return false;
  26. }
  27. void _isShowText(){
  28. if (mIsExpaned){
  29. setState(() {
  30. mIsExpaned = false;
  31. });
  32. }
  33. else {
  34. setState(() {
  35. mIsExpaned = true;
  36. });
  37. }
  38. }
  39. // ignore: non_constant_identifier_names
  40. Widget _RichText(String _text,width){
  41. if (isExpaned(_text, width)){
  42. if (mIsExpaned){
  43. return Text.rich(
  44. TextSpan(
  45. text: _text,
  46. style: TextStyle(color: Colors.white,fontSize:14.0),
  47. children: [
  48. TextSpan(
  49. text: '收起',
  50. style: TextStyle(color: Colors.white),
  51. recognizer: TapGestureRecognizer()..onTap = ()async{
  52. _isShowText();
  53. }
  54. )
  55. ]
  56. )
  57. );
  58. }
  59. else {
  60. return Stack(
  61. children: [
  62. Text(_text,style: TextStyle(color: Colors.white,fontSize: 14),
  63. maxLines: 2,textAlign: TextAlign.left,overflow: TextOverflow.ellipsis,),
  64. Positioned(bottom: 0,right: 0,child: GestureDetector(
  65. onTap: (){
  66. _isShowText();
  67. },
  68. child: Container(
  69. width: 50,
  70. child: Text('展开'),
  71. ),
  72. ))
  73. ],
  74. );
  75. }
  76. }
  77. else {
  78. return Text(
  79. _text,
  80. maxLines: 2,
  81. textAlign: TextAlign.left,
  82. overflow: TextOverflow.ellipsis,
  83. );
  84. }
  85. }
  86. @override
  87. Widget build(BuildContext context) {
  88. return _RichText(widget.text, widget.width);
  89. }
  90. }