You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter GridView使用TextSpan报错:类型TextSpan无法赋值给Widget列表

问题原因
  • 报错The element type 'TextSpan' can't be assigned to the list type 'Widget'的核心是**TextSpan不是Widget类型**,它是用于描述文本片段的配置对象,仅可作为Text、RichText等文本渲染组件的入参使用,无法直接作为布局类组件(比如GridView)的子节点。
  • 你删除children后的<Widget>泛型声明只是绕开了编译期的显式类型检查,运行时依然会因为类型不匹配报错,没有解决本质问题。
修复方案

把每个TextSpan外层包裹Text组件即可,如果是单个独立文本没有嵌套其他TextSpan,也可以直接简化为Text组件写法,省略TextSpan层级。
修改后代码参考:

child: GridView.count(
  primary: false,
  padding: const EdgeInsets.all(20),
  crossAxisSpacing: 10,
  mainAxisSpacing: 10,
  crossAxisCount: 4, // 4 tiles horizontally
  children: <Widget>[
    // 写法1:保留TextSpan,用Text.rich承载
    Text.rich(
      TextSpan(
        text: widget.result + '  ',
        style: TextStyle(
          fontSize: 20.0,
          fontWeight: FontWeight.bold,
          color: checkdominantA(widget.predominant, widget.result),
          height: 2.5,
          letterSpacing: 0.7,
        ),
      ),
    ),
    // 写法2:单文本场景直接用Text,更简洁
    Text(
      widget.result2 + '  ',
      style: TextStyle(
        fontSize: 20.0,
        fontWeight: FontWeight.bold,
        color: checkdominantA(widget.predominant, widget.result2),
        height: 2.5,
        letterSpacing: 0.7,
      ),
    ),
    // 剩余14个文本项同理处理即可
  ],
),

内容的提问来源于stack exchange,提问作者bilbo_bo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 04:45:03