Flutter解析API返回的JSON动态列表出现类型不匹配报错如何解决?
报错原因
- 第一个直接触发报错的点:你定义的
Map<String, Data>要求key为String类型,但JSON中返回的value['id']是int类型,赋值给Map的key时触发类型不匹配,对应日志里的type 'int' is not a subtype of type 'String'错误。 - 第二个隐藏的逻辑错误:你后续直接执行
_list = map as List<Data>强制类型转换,Map和List是完全不同的集合结构,即使解决了key类型问题,这一步也会抛出类型转换异常。 - 额外说明:你当前的需求是渲染列表,API返回的本身就是有序的列表结构,不需要额外用Map存储数据,直接转成List即可满足需求。
修复方案
方案1:不需要ID去重的场景(推荐,适配你当前的需求)
直接修改DataModel类的fetchData方法即可:
Future<void> fetchData() async { final url = Uri.parse('https://jsonplaceholder.typicode.com/albums'); final response = await http.get(url); // 先将解码结果强转为List<dynamic>类型 final extractedData = json.decode(response.body) as List<dynamic>; List<Data> tempList = []; for (var value in extractedData) { tempList.add(Data( userId: value['userId'] as int, id: value['id'] as int, title: value['title'] as String, )); } _list = tempList; notifyListeners(); }
方案2:需要通过ID去重的场景
如果你确实需要保留Map去重的逻辑,修改对应代码即可:
Future<void> fetchData() async { final url = Uri.parse('https://jsonplaceholder.typicode.com/albums'); final response = await http.get(url); final extractedData = json.decode(response.body) as List<dynamic>; // 将Map的key类型改为int适配id的类型 Map<int, Data> map = {}; for (var value in extractedData) { map.putIfAbsent( value['id'] as int, () => Data( userId: value['userId'] as int, id: value['id'] as int, title: value['title'] as String, ) ); } // 提取Map的所有值转为列表,不要直接强转Map为List _list = map.values.toList(); notifyListeners(); }
UI层写法确认
你在MainScreen中通过provider[index].userId、provider[index].id、provider[index].title取值的写法完全正确,修复Model层代码后即可正常渲染列表。
内容的提问来源于stack exchange,提问作者coolhack7
相关产品推荐
相关产品推荐

