flutter 获取文本中字符串溢出点的长度

kx1ctssn  于 2023-01-18  发布在  Flutter
关注(0)|答案(2)|浏览(110)

我在一个文本小部件中有一个长字符串。我将小部件放置在一个SizedBox小部件中,具有固定的宽度,并且我将文本小部件 *,的, *maxLines设为4。是否有办法获得显示的字符串的长度?也就是说,我想获得在使用TextOverflow之前屏幕上显示的字符数。

7jmck4yq

7jmck4yq1#

  • 循环是昂贵的,希望你能找到另一种方法。
test() {
    var str = '''
    Flutter transforms the app development process. Build, test, 
    and deploy beautiful mobile, web, desktop, and embedded apps
    from a single codebase.''';

    print(hasTextOverflow(str, TextStyle(fontSize: 14), 100, 300, 4)); // true
  }

  bool hasTextOverflow(String text, TextStyle style, double minWidth,
      double maxWidth, int maxLines) {
    final TextPainter textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      maxLines: maxLines,
      textDirection: TextDirection.ltr,
    )..layout(minWidth: minWidth, maxWidth: maxWidth);
    return textPainter.didExceedMaxLines;
  }
rsaldnfx

rsaldnfx2#

你可以使用TextPainter来完成这个任务,它允许你单独绘制一个文本,并且它负责绘制Text小部件:

// This is the text we are testing with
      String text = 'Text Example';
      
      // This is the width of the SizedBox/Container
      double width = 30;
      
      // maxLines of widget
      int maxLines = 2;

      // and here is the TextPainter declaration
      TextPainter textPainterExample = TextPainter(
        text: TextSpan(
          text: text,
        ),
        textDirection: TextDirection.ltr,
        maxLines: maxLines,
      );
      
      // we simulate the painting of that text and get registered information about it such as offsets...
      textPainterExample.layout(maxWidth: width);
    
      // and this is the index of the letter which starts overflowing on
      final indexOfOverflowing = textPainterExample.getPositionForOffset(Offset(width, 0)).offset;

现在你已经得到了文本开始溢出的indexOfOverflowing,你可以简单地substring它,如下所示:

String limitedText = text.substring(0, indexOfOverflowing);

现在您可以使用limitedText

相关问题