1

I have a long String inside a Text Widget. I have placed the widget inside a SizedBox widget with some fixed width, and I have given the Text Widget a maxLines of 4. Is there a way to get the length of the displayed string? I.e., I want to get the number of characters that were displayed on the screen, before TextOverflow was used.

Miro
  • 364
  • 1
  • 12

2 Answers2

2

You can use the TextPainter for this, it allows you to get paint separately a text, and it is responsible for painting the Text widget :

      // 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;

and now that you got that indexOfOverflowing where the text starts overflowing, you can simply substring it like this:

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

and you can use now the limitedText.

Gwhyyy
  • 7,554
  • 3
  • 8
  • 35
1
  • Looping is expensive, and hopefully you can find another way.
  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;
  }



bakboem
  • 534
  • 4
  • 12