Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

dart - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you simply want to check for how many newlines the text contains, you can do a simple

final numLines = '
'.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, size) {
  final span = TextSpan(text: yourText, style: yourStyle);
  final tp = TextPainter(text: span, maxLines: 3);
  tp.layout(maxWidth: size.maxWidth);

  if (tp.didExceedMaxLines) {
    // The text has more than three lines.
    // TODO: display the prompt message
    return Container(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...