How to set read more less in Flutter?

Prafulla Singh
2 min readApr 26, 2020
read more/less

This is explanation of my answer in StackOverflow. To show read more/less our Text Widget will have two states.

  1. See Less
  2. See More

See less is easy, As we have to append the clickable text at the end of the string using TextSpan.

TextSpan link = TextSpan(
text: _readMore ? "... read more" : " read less",
style: TextStyle(
color: colorClickableText,
),
recognizer: TapGestureRecognizer()..onTap = _onTapLink
);

For See More, We need to calculate how much text can be inserted in a given number of lines or Space. After calculating there can be two cases.

  1. The text is too small and fits perfectly in the given space. In this case, we do not need to add see more or see less.
  2. If text is big enough to show see more/less. We need to strip the text to make space to make see more text.

For the calculation of the amount of text can be inserted, we can use TextPainter like following:

//get size of see more see less
TextPainter textPainter = TextPainter(
text: link,
textDirection: TextDirection.rtl,//better to pass this from master widget if ltr and rtl both supported
maxLines: widget.trimLines,
ellipsis: '...',
);
textPainter.layout(minWidth…

--

--