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

Flutter构建TextSpan子元素报错:List无法赋值给InlineSpan类型

问题修复方案

错误原因分析

你遇到的error: The element type 'List' can't be assigned to the list type 'InlineSpan'错误,核心原因是TextSpan的children参数被错误嵌套了列表:你把childrenTextSpan这个List又放进了另一个List里(children: [childrenTextSpan]),但children需要的是List<InlineSpan>类型,而非List<List<InlineSpan>>。

另外代码还有两个隐性问题:

  • else分支创建了TextSpan但未添加到childrenTextSpan,会导致非目标单词丢失
  • 按空格分割句子后,单词间的空格被移除,最终文本会连在一起(比如"I"和"Love"会变成"ILove")

修复后的完整代码

class UnderlineMe extends StatelessWidget {
  final String sentence;
  final String underline;
  const UnderlineMe(
      {super.key, required this.sentence, required this.underline});
  @override
  Widget build(BuildContext context) {
    var splitSentence = sentence.split(' ');
    List<InlineSpan> childrenTextSpan = [];
    for (var i = 0; i < splitSentence.length; i++) {
      final word = splitSentence[i];
      if (word == underline) {
        childrenTextSpan.add(TextSpan(
            text: word,
            style: const TextStyle(
              decoration: TextDecoration.underline,
            )));
      } else {
        // 将非目标单词的TextSpan加入列表
        childrenTextSpan.add(TextSpan(text: word));
      }
      // 给除最后一个单词外的所有单词添加分隔空格
      if (i != splitSentence.length - 1) {
        childrenTextSpan.add(const TextSpan(text: ' '));
      }
    }
    return Text.rich(
      TextSpan(
        // 直接传入childrenTextSpan,无需额外嵌套列表
        children: childrenTextSpan,
      ),
    );
  }
}

关键修改点

  • 移除children参数外的嵌套列表,直接使用children: childrenTextSpan
  • 在else分支添加childrenTextSpan.add(...),保留非目标单词
  • 循环中加入空格处理逻辑,确保单词间的分隔正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:33:16