Flutter中嵌套列表对象映射报错求助
Flutter嵌套Standing对象列表映射报错排查与解决
常见错误原因及修正方案
1. 模型类定义不匹配
确保League类正确声明嵌套的Standing列表类型,避免类型不匹配报错:
class League { final String name; final List<List<Standing>> standings; // 明确为双层嵌套列表 League({required this.name, required this.standings}); factory League.fromJson(Map<String, dynamic> json) { // 逐层解析嵌套结构 final List<dynamic> standingsGroups = json['standings']; final List<List<Standing>> parsedStandings = standingsGroups.map((group) { return (group as List<dynamic>).map((item) => Standing.fromJson(item)).toList(); }).toList(); return League( name: json['name'] as String, standings: parsedStandings, ); } } class Standing { final String teamName; final int points; Standing({required this.teamName, required this.points}); factory Standing.fromJson(Map<String, dynamic> json) { return Standing( teamName: json['team']['name'] as String, points: json['points'] as int, ); } }
2. 数据解析时遗漏类型转换
多数报错源于解析时未将嵌套的dynamic列表逐层转为目标类型,比如省略内层toList()操作,导致返回Iterable而非List。
3. UI映射时未转List
在Flutter Widget中使用map生成子组件时,必须将Iterable转为List,否则会抛出类型错误:
// 正确写法 Column( children: league.standings.map((group) { return Column( children: group.map((standing) { return ListTile( title: Text(standing.teamName), trailing: Text('${standing.points}'), ); }).toList(), // 必须转为List ); }).toList(), )
4. 空安全处理
如果接口返回的standings可能为null,需添加空判断避免空指针:
factory League.fromJson(Map<String, dynamic> json) { final List<dynamic>? standingsGroups = json['standings']; final List<List<Standing>> parsedStandings = standingsGroups?.map((group) { return (group as List<dynamic>).map((item) => Standing.fromJson(item)).toList(); }).toList() ?? []; return League( name: json['name'] as String, standings: parsedStandings, ); }
快速排查步骤
- 打印解析后的
league.standings.runtimeType,确认是否为List<List<Standing>> - 检查UI层
map操作后是否调用toList() - 对比JSON数据结构与模型类字段,确认嵌套层级完全匹配
内容的提问来源于stack exchange,提问作者Taki
相关产品推荐
相关产品推荐

