Flutter:如何获取文本行数 [英] Flutter: How to Get the Number of Text Lines

查看:1831
本文介绍了Flutter:如何获取文本行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取文本行数
在我们的Flutter项目中,我们需要确定文本行数是否超过3,然后将显示提示消息。我们如何使用代码来实现它?

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?

推荐答案

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

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.

这篇关于Flutter:如何获取文本行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆