【问题标题】:Flutter's TextPainter throws an '!_needsLayout': is not true.' exceptionFlutter 的 TextPainter 抛出一个 '!_needsLayout': is not true。例外
【发布时间】:2021-07-13 02:32:35
【问题描述】:

我尝试使用TextPainter 来获取文本小部件中字符串的最大长度,但如果我调用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;
  }

完整文件

see this file on GitHub

【问题讨论】:

  • 当我关闭键盘并很快选择新的东西时,我也遇到了这个异常,我猜它加载了一些查询手机尺寸的东西,但我的代码中没有类似的东西。跨度>

标签: android flutter dart flutter-android


【解决方案1】:

在调用layout 之前,不会计算绘制文本的大小。这必须在访问任何与大小相关的属性(如 didExceedMaxLines)之前完成。

更多信息请咨询API documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2022-12-01
    • 2012-02-16
    • 2019-06-22
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多