Flutter's TextPainter throws an '!_needsLayout': is not true.' exception

Issue

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.

Solution

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.

Answered By – hacker1024

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *