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.

1
  • 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. Nov 11, 2021 at 13:43

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.