4

I try to use a TextPainter to get the maximum length of a string in a Text Widget, but if I call the painter, it will throw an !_needsLayout': is not true. exception.

Exception

The following assertion was thrown building FeedPage(dirty, dependencies: [MediaQuery], state: _FeedPageState#9c489):
'package:flutter/src/painting/text_painter.dart': Failed assertion: line 546 pos 12: '!_needsLayout': is not true.

Method with TextPainter

int maxCharCountToFit(String content) {
    List<String> splitted = content.split(" ");

    for (int i = splitted.length; i >= 0; i--) {
      bool retry = TextPainter(
            text: TextSpan(text: splitted.sublist(0, splitted.length - i).join(" "), style: pageTextStyle),
            maxLines: 25,
            textScaleFactor: MediaQuery.of(context).textScaleFactor,
            textDirection: TextDirection.ltr,
          ).didExceedMaxLines ==
          false;

      if (retry == false) {
        return splitted.sublist(0, i).length;
      }
    }

    return 0;
  }

Complete file

Please see this file on GitHub.

Tobonaut
  • 2,245
  • 2
  • 26
  • 39
  • Im also getting this exception when I dismiss a keyboard and select something new very quickly, I guess its loading something that queries the phone dimensions but I don't have anything like that in my code. – martinseal1987 Nov 11 '21 at 13:43

1 Answers1

6

The size of the painted text is not calculated until you call layout. This must be done before accessing any size-related properties like didExceedMaxLines.

Consult the API documentation for more information.

hacker1024
  • 3,186
  • 1
  • 11
  • 31