Home > Mobile >  Get the length of a string inside a text at the point where it overflows
Get the length of a string inside a text at the point where it overflows

Time:01-15

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.

CodePudding user response:

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



CodePudding user response:

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.

  • Related