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

3,367

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.

Share:
3,367
Tobonaut
Author by

Tobonaut

Bavarian, MacHead, Big Data, Software Engineer.

Updated on December 29, 2022

Comments

  • Tobonaut
    Tobonaut over 1 year

    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.