Flutter调用REST API拉取列表数据报_TypeError类型错误如何解决?
错误根本原因
两个报错本质都是类型不匹配问题,具体错误点如下:
- 第一次报错是你直接遍历
http.get返回的Response对象,该对象是请求响应封装类,不是接口返回的JSON数据,本身不支持遍历。 - 第二次报错是你解码响应体得到的是
Map<String, dynamic>类型,但你定义的_listAll是List类型,二者结构不匹配无法直接赋值。 - 额外隐藏问题:你的
TransactionModel的fromJson方法没有处理嵌套模型转换,直接赋值后续也会触发类型错误。
修复步骤
1. 先明确接口返回结构
你解码后的JSON是Map结构,分两种常见场景处理:
- 场景A:接口返回的Map本身就是单条交易数据 → 修改
_listAll类型为TransactionModel?,不需要用List - 场景B:接口返回的Map中某一个字段存储交易列表(比如常见的
data、list字段)→ 取对应字段的数组转模型
2. 修正请求方法
以场景B(接口返回结构为{"code":xxx,"data":[交易列表],"msg":xxx})为例,修正后的代码如下:
late List<TransactionModel> _listAll; late List<TransactionModel> _displayList; void _listTransaction() async { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("userToken") ?? ""; final response = await http.get( Uri.parse('替换为你的接口地址'), headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': token, }, ); if (response.statusCode == 200) { final Map<String, dynamic> resData = json.decode(response.body); // 此处的['data']替换为你接口中实际存储列表的字段名 final List<dynamic> rawList = resData['data'] as List; _listAll = rawList.map((item) => TransactionModel.fromJson(item)).toList(); setState(() { _displayList = _listAll; }); } }
3. 修正TransactionModel定义
class TransactionModel { int? month; int? year; double? balanceFull; double? balanceMonth; ExpenseModel? expenseModel; RevenueModel? revenueModel; TransactionModel({ this.month, this.year, this.balanceFull, this.balanceMonth, this.expenseModel, this.revenueModel, }); TransactionModel.fromJson(Map<String, dynamic> json) { month = json['month'] as int?; year = json['year'] as int?; // 统一做数字类型兼容,避免接口返回int时转double报错 balanceFull = (json['balanceFull'] as num?)?.toDouble(); balanceMonth = (json['balanceMonth'] as num?)?.toDouble(); // 嵌套模型需调用对应fromJson转换 expenseModel = json['expenseModel'] != null ? ExpenseModel.fromJson(json['expenseModel']) : null; revenueModel = json['revenueModel'] != null ? RevenueModel.fromJson(json['revenueModel']) : null; } }
如果是场景A,只需要把请求方法中模型赋值逻辑改为:
_listAll = TransactionModel.fromJson(resData);
同时修改_listAll的定义为TransactionModel? _listAll;即可。
内容的提问来源于stack exchange,提问作者E. Biagi
相关产品推荐
相关产品推荐

