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

Flutter中如何访问复杂List第二个元素的content字段?

解决Dart复杂List数据访问与ListView构建问题

首先你的数据结构如下:

class DataList {
  static List<Map<String, dynamic>> computerData = [
    {
      "maintopic": "Computer Software",
      "subtopic": [
        {
          "topic": "introduction",
          "content": "owhrfiuwbef iosevibskvsuibvisncsd\nnisudvusvc"
        }
      ]
    },
    {
      "maintopic": "Computer",
      "subtopic": [
        {
          "topic": "introduction",
          "content": "owhrfic"
        },
      ]
    }
  ];
}

直接获取第二个元素的content值

要访问第二个maintopic(对应"Computer")的content,直接通过索引层级访问即可:

// 第二个主元素在List的索引为1,其subtopic列表的第一个元素索引为0
String targetContent = DataList.computerData[1]['subtopic'][0]['content'];
// 最终结果为 "owhrfic"

修复ListView.builder的代码

你的原代码存在几个问题:forEach无返回值,无法用...展开到Widget列表;错误访问不存在的data['subtopic']字段;ListView.builder参数格式错误。修正后的代码如下:

ListView.builder(
  itemCount: DataList.computerData.length,
  itemBuilder: (context, index) {
    List<Map<String, dynamic>> subtopics = DataList.computerData[index]['subtopic'];
    return Container(
      padding: EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 显示主标题
          Text(
            DataList.computerData[index]['maintopic'],
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 8),
          // 遍历子话题并转换为Widget
          ...subtopics.map((subtopic) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(subtopic['topic'], style: TextStyle(fontSize: 16)),
                Text(subtopic['content'], style: TextStyle(fontSize: 14)),
                SizedBox(height: 8),
              ],
            );
          }).toList(),
        ],
      ),
    );
  },
)

这段代码会逐个渲染每个主话题,同时展开显示其下所有子话题的topic和content内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:50:11