Flutter/Dart HTTP请求类型转换异常:如何修复该报错?
修复Flutter/Dart HTTP请求类型转换异常方案
问题根源
报错type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast的核心原因:接口返回的是单个JSON对象,但你的代码错误地将其强制转换为List类型,导致类型不匹配。
修复步骤
1. 确认接口返回格式
先明确接口返回的JSON结构(示例):
{ "year": 2024, "totalAmount": 3200.5, "bills": [ {"id": 1, "title": "餐饮", "amount": 1800}, {"id": 2, "title": "交通", "amount": 600} ] }
该结构是单个对象(外层为{}),而非数组(外层为[]),这是关键前提。
2. 修正请求解析代码
把原来强制转List的逻辑,改为解析为Map<String, dynamic>,再传入实体类的fromJson方法:
import 'dart:convert'; import 'package:http/http.dart' as http; final response = await http.get(Uri.parse('你的接口地址')); if (response.statusCode == 200) { // 正确:将响应解析为Map对象,而非List Map<String, dynamic> responseData = jsonDecode(response.body) as Map<String, dynamic>; YearBill yearBill = YearBill.fromJson(responseData); // 后续处理yearBill实例 } else { throw Exception('请求失败,状态码:${response.statusCode}'); }
3. 适配实体类的fromJson方法
确保YearBill的fromJson方法接收Map<String, dynamic>参数,内部正确处理嵌套数组:
class YearBill { final int year; final double totalAmount; final List<Bill> bills; YearBill({ required this.year, required this.totalAmount, required this.bills, }); factory YearBill.fromJson(Map<String, dynamic> json) { return YearBill( year: json['year'] as int, totalAmount: (json['totalAmount'] as num).toDouble(), // 处理嵌套的bills数组:先转List再映射为Bill对象 bills: (json['bills'] as List<dynamic>) .map((billJson) => Bill.fromJson(billJson as Map<String, dynamic>)) .toList(), ); } } class Bill { final int id; final String title; final double amount; Bill({ required this.id, required this.title, required this.amount, }); factory Bill.fromJson(Map<String, dynamic> json) { return Bill( id: json['id'] as int, title: json['title'] as String, amount: (json['amount'] as num).toDouble(), ); } }
额外优化建议
为避免类型转换异常扩散,可使用可选类型转换并设置默认值:
year: json['year'] as? int ?? 0, totalAmount: (json['totalAmount'] as? num ?? 0).toDouble(),
内容的提问来源于stack exchange,提问作者Bill Tertis
相关产品推荐
相关产品推荐

