Flutter: How to Get the Number of Text Lines

If you simply want to know how many intrinsic lines the text contains, you can do a simple

final numLines="\n".allMatches(yourText).length + 1;

However, I guess you’re more interested in the number of lines that are actually being displayed visually.
Here, things get a little more complicated, because you need to know the available space (the BoxConstraints) in order to calculate how many lines the text needs.
To do that, you can use a LayoutBuilder to delay the widget building and a TextPainter to do the actual calculation:

return LayoutBuilder(builder: (context, constraints) {
  final span = TextSpan(text: yourText, style: yourStyle);
  final tp = TextPainter(text: span, textDirection: TextDirection.ltr);
  tp.layout(maxWidth: constraints.maxWidth);
  final numLines = tp.computeLineMetrics().length;

  if (numLines > 3) {
    // TODO: display the prompt message
    return ColoredBox(color: Colors.red);
  } else {
    return Text(yourText, style: yourStyle);
  }
});

I extracted some of the code from the auto_size_text pub package, which might also be interesting to you:
It sizes its text so it fits in the given space.

Anyhow, be careful when displaying the prompt:
Your widget’s build method may be called several times per second, resulting in multiple prompts being displayed simultaneously.

Note: The computeLineMetrics() function was added after the initial version of the answer. That’s why a previous version of this answer used a TextPainter(text: span, maxLines: 3) and then checked if tp.didExceedMaxLines.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)