且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Flutter:如何获取文本行数

更新时间:2022-12-22 14:59:56

如果您只想检查文本包含多少个换行符,您可以可以做一个简单的

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

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

但是,我想您对实际显示的行数更感兴趣。
在这里,事情变得有些复杂,因为您需要知道可用空间( BoxConstraints )以便计算文本需要多少行。
为此,您可以使用 LayoutBuilder 延迟窗口小部件的构建,并使用 TextPainter 来完成实际计算:

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);
  }
});

我从 auto_size_text pub包,这可能对您也很有趣:
调整文本大小以便适合给定的空间。

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.

无论如何,显示提示时要小心:
小部件的 build 方法可能每秒被调用几次,导致同时显示多个提示。

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.