Search code examples
dartflutterflutter-layout

Flutter: How to Get the Number of Text Lines


How to Get the Number of Text Lines In our Flutter project, we need to determine if the number of lines of text exceeds 3, then we will display a prompt message. How can we use the code to implement it?


Solution

  • 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.