如何解决Flutter 的 TextPainter 抛出一个 '!_needsLayout': is not true例外
我尝试使用 TextPainter
来获取 Text Widget 中字符串的最大长度,但是如果我调用 Painter,它会抛出 !_needsLayout': is not true.
异常。
例外
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.
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;
}
完整文件
解决方法
在调用 layout
之前,不会计算绘制文本的大小。这必须在访问任何与尺寸相关的属性(如 didExceedMaxLines
)之前完成。
有关详细信息,请咨询 API documentation。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。