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

Flutter遍历children数组出错,如何用Text组件展示列表数据?

问题修复方案

错误原因

你在for循环里用了大括号{},这会把循环内的Text组件包裹成一个Set<Text>集合,但Row的children属性要求是Widget类型的列表,类型不匹配导致报错。

修复方法

方法1:移除多余的大括号

直接去掉for循环后的大括号,让循环直接返回Text组件:

List myList = [{"id":27,"name":"Horror"},{"id":9648,"name":"Mystery"},{"id":53,"name":"Thriller"}];

// ...

Container(
  child: Row(
    children: [
      for(var i = 0; i < myList.length; i++)
        Text("VALUE:" + myList[i]['name']),
    ],  
  ),  
),

方法2:使用map遍历列表(更简洁的Flutter风格)

用map方法遍历列表,将每个元素转为Text组件,最后转成List(因为map返回的是Iterable,需要转成List才能赋值给children):

Container(
  child: Row(
    children: myList.map((item) {
      return Text("VALUE:" + item['name']);
    }).toList(),
  ),  
),

如果想更简洁,还可以用箭头函数:

Container(
  child: Row(
    children: myList.map((item) => Text("VALUE:" + item['name'])).toList(),
  ),  
),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:47:12