Flutter/Dart中如何获取嵌套数组interests的所有元素?
如何获取嵌套数组中interests的所有记录并在StreamBuilder中正确展示?
你拿到的JSON结构如下:
{ "interests": [ { "id": 1, "name": "Fashion" }, { "id": 2, "name": "Art" } ] }
你目前的问题是只能通过索引获取单个元素,且StreamBuilder中的遍历逻辑存在错误,以下是修复方案:
1. 正确提取并传递interests数组
你之前把整个解析后的Map传给了StreamController,但实际上我们需要的是其中的interests数组。修改网络请求后的代码:
var data = convert.json.decode(response.body); // 打印所有interests的name,验证是否获取到全部数据 for (var interest in data["interests"]) { print(interest["name"].toString()); } if (response.statusCode == 200) { // 传递interests数组而不是整个Map streamControllerforInterestList.add(data["interests"]); }
2. 修复StreamBuilder中的遍历错误
你的StreamBuilder指定了泛型StreamBuilder<List>,但遍历和数据处理有两个问题:
- 错误使用了双层方括号
document[["id"]],应该用单层方括号document["id"]来获取Map中的值 - 需要将Map数据转换为
Interest类型的对象(因为你的MultiSelectChipField泛型是Interest?)
首先确保你有Interest模型类:
class Interest { final int id; final String name; Interest({required this.id, required this.name}); }
然后修改StreamBuilder的代码:
StreamBuilder<List>( stream: streamControllerforInterestList.stream, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return MultiSelectChipField<Interest?>( items: [ // 遍历interests数组,将每个Map转为Interest对象并生成MultiSelectItem for (Map<String, dynamic> document in snapshot.data) MultiSelectItem<Interest>( Interest(id: document["id"], name: document["name"]), document["name"] ) ].toList(), icon: const Icon( Icons.clear, color: Colors.black, ), showHeader: false, scroll: false, decoration: const BoxDecoration(), selectedChipColor: HexColor('#FFB7E1').withOpacity(0.5), selectedTextStyle: const TextStyle(color: Color.fromARGB(255, 0, 0, 0)), onTap: (values) { // 处理选中逻辑 }, ); } return Container( padding: const EdgeInsets.only(top: 20), child: const Row( children: [ Text( '加载兴趣中...', style: TextStyle( color: Colors.grey, fontSize: 14, ), ), ], ), ); }, ),
关键说明
- 传递给StreamController的必须是
data["interests"],这样snapshot.data才是一个包含所有兴趣的数组 - 遍历数组时,每个元素是Map类型,通过
document["key"]获取对应值 - 必须将Map转换为
Interest对象,才能匹配MultiSelectChipField的泛型要求
内容的提问来源于stack exchange,提问作者Flochristos
相关产品推荐
相关产品推荐

