Flutter/Dart中如何遍历JSON API返回的Map列表获取全部赛事数据
解决方案
1. 重构Competition模型类
拆分原有的解析逻辑,让单个赛事解析与批量列表解析分离,彻底移除硬编码的索引[0]:
class Competition { int id; String name; String code; String type; String emblem; Competition({ required this.id, required this.name, required this.code, required this.type, required this.emblem, }); // 从单个match对象的competition字段解析单条赛事信息 factory Competition.fromMatchJson(Map<String, dynamic> matchData) { final compData = matchData["competition"]; return Competition( id: compData['id'], name: compData['name'], code: compData['code'], type: compData['type'], emblem: compData['emblem'], ); } // 批量解析整个matches列表,返回所有赛事数据 static List<Competition> parseMatches(List<dynamic> matchesList) { return matchesList.map((match) => Competition.fromMatchJson(match)).toList(); } }
2. 修改API服务类
调整返回类型为Future<List<Competition>>,调用批量解析方法一次性获取全部赛事:
import 'dart:convert'; import 'package:http/http.dart' as http; class ServiceApi { Future<List<Competition>> getMatches() async { final response = await http.get( Uri.parse('_url'), // 替换为实际API地址 headers: {'X-Auth-Token': '_key'}, // 替换为实际授权Token ); final Map<String, dynamic> data = jsonDecode(response.body); final List<dynamic> matches = data["matches"]; return Competition.parseMatches(matches); } }
关键修改说明
- 移除硬编码索引:原
fromJson依赖matches[0]仅能获取单条数据,现在改为从每个match对象独立解析,遍历列表即可覆盖全部赛事。 - 修正返回类型:API服务从返回单个
Competition改为返回List<Competition>,完全匹配“获取全部赛事”的需求。 - 修复原代码错误:修正了变量拼写错误、未定义返回变量等问题。
内容的提问来源于stack exchange,提问作者milano zz
相关产品推荐
相关产品推荐

