Reputation: 2485
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.
Upvotes: 4
Views: 6674
Reputation: 3668
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.
Upvotes: 6