Skip to content

Instantly share code, notes, and snippets.

@vasyafromrussia
Created March 14, 2020 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasyafromrussia/d9d5630553153064d7ab0a9cf1abcf97 to your computer and use it in GitHub Desktop.
Save vasyafromrussia/d9d5630553153064d7ab0a9cf1abcf97 to your computer and use it in GitHub Desktop.
Flutter expandable text step 3
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