Flutter API请求报错:_InternalLinkedHashMap非List<dynamic>子类型
问题解决:_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List'
这个报错的核心原因是你假设API返回的是直接的数组,但实际返回的是一个JSON对象,强行把对象转成List就会触发类型不匹配错误。
解决步骤:
先打印
response.body确认API返回的实际结构,比如可能是类似这样的格式:{ "data": [ {"id": 1, ...}, {"id": 2, ...} ] }(列表被包裹在某个对象字段里,比如
data或者factures)修改代码,先把解码结果转成Map,再取出对应的列表字段:
- 注意
json.decode是同步方法,不需要加await,之前的await是多余的。
- 注意
修改后的完整代码:
Future<List<FactureModel>> getUser() async { var apiUrl = '/factures'; http.Response response = await http.get(Uri.parse(_baseUrl + apiUrl)); try { if (response.statusCode == 200) { // 先转成Map,再取出对应的列表字段(这里假设字段是'factures',根据实际返回调整) Map<String, dynamic> responseMap = json.decode(response.body); List<dynamic> list = responseMap['factures']; print(list); return list.map((e) => FactureModel.fromJson(e)).toList(); } else { print("Something wrong"); return <FactureModel>[]; } } catch (e) { print(e); print("Api request failed"); // 修正原代码拼写错误 return <FactureModel>[]; } }
- 如果不确定API返回结构,直接打印
response.body就能看到真实的JSON格式,对应调整取出列表的字段名即可。
内容的提问来源于stack exchange,提问作者Bondoguy
相关产品推荐
相关产品推荐

