Created
March 14, 2020 12:07
-
-
Save vasyafromrussia/d9d5630553153064d7ab0a9cf1abcf97 to your computer and use it in GitHub Desktop.
Flutter expandable text step 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class _ExpandableTextState extends State<ExpandableText> { | |
static const String _ellipsis = "\u2026\u0020"; | |
String get _lineEnding => "$_ellipsis${widget.moreSpan.text}"; | |
// ... | |
@override | |
Widget build(BuildContext context) => LayoutBuilder( | |
builder: (context, constraints) { | |
final maxLines = widget.maxLines; | |
final richText = Text.rich(widget.textSpan).build(context) as RichText; | |
final boxes = richText.measure(context, constraints); | |
if (boxes.length <= maxLines || _isExpanded) { | |
return RichText(text: widget.textSpan); | |
} else { | |
final croppedText = _ellipsizeText(boxes); | |
final ellipsizedText = _buildEllipsizedText(croppedText, _tapRecognizer); | |
if (ellipsizedText.measure(context, constraints).length <= maxLines) { | |
return ellipsizedText; | |
} else { | |
final fixedEllipsizedText = croppedText.substring(0, croppedText.length - _lineEnding.length); | |
return _buildEllipsizedText(fixedEllipsizedText, _tapRecognizer); | |
} | |
} | |
}, | |
); | |
String _ellipsizeText(List<TextBox> boxes) { | |
final text = widget.textSpan.text; | |
final maxLines = widget.maxLines; | |
double _calculateLinesLength(List<TextBox> boxes) => boxes.map((box) => box.right - box.left).reduce((acc, value) => acc += value); | |
final requiredLength = _calculateLinesLength(boxes.sublist(0, maxLines)); | |
final totalLength = _calculateLinesLength(boxes); | |
final requiredTextFraction = requiredLength / totalLength; | |
return text.substring(0, (text.length * requiredTextFraction).floor()); | |
} | |
RichText _buildEllipsizedText(String text, GestureRecognizer tapRecognizer) => RichText( | |
text: TextSpan( | |
text: "$text$_ellipsis", | |
style: widget.textSpan.style, | |
children: [widget.moreSpan], | |
), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment