Flutter中TextField添加WidgetSpan出现'dimensions != null'报错如何解决?
报错修复方案
报错核心原因:
dimensions != null断言触发是因为重写buildTextSpan方法时未传入原生 required 的样式参数,也没有处理输入法候选词的 composing 区域测量逻辑,导致文本布局阶段无法拿到正确的尺寸参数。
可直接运行的修复代码
@override TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing}) { final atIndex = text.indexOf('@'); if (atIndex == -1) { // 不需要替换@的场景直接走父类原生逻辑,避免手动处理composing出错 return super.buildTextSpan( context: context, style: style, withComposing: withComposing ); } final List<InlineSpan> spans = []; // 所有TextSpan都要继承传入的style参数 spans.add(TextSpan(text: text.substring(0, atIndex), style: style)); spans.add( WidgetSpan( alignment: PlaceholderAlignment.middle, // 显式指定基线匹配文本,避免测量异常 baseline: TextBaseline.alphabetic, child: Card( margin: EdgeInsets.zero, child: Padding( padding: const EdgeInsets.all(4.0), child: Text('@', style: style), ), ), ), ); spans.add(TextSpan(text: text.substring(atIndex + 1), style: style)); return TextSpan( style: style, children: spans, ); }
备选临时解决方案
- 如果修改后仍有报错,可以在返回TextSpan前强制忽略composing逻辑:把调用父类方法时的
withComposing参数固定设为false,适合不需要输入法候选词高亮的业务场景 - 规避方案:不用WidgetSpan实现,改用TextSpan自定义样式模拟标签效果,给@字符单独设置背景、圆角、内边距样式,完全避开WidgetSpan的测量问题
- 版本升级:该问题在Flutter 3.10及以上稳定版已修复大部分触发场景,若当前使用的Flutter版本较低,可尝试升级后验证
内容的提问来源于stack exchange,提问作者derkro99
相关产品推荐
相关产品推荐

