Flutter使用dio解析API响应报错:List不是Map<String,dynamic>子类型
解决Flutter解析JSON数组时"type 'List' is not a subtype of type 'Map<String, dynamic>'"错误
问题原因
你的API返回的是JSON数组(List类型),但直接用Mapper.fromJson(response.data).toObject<List<BottomNavListItem>>()解析是错误的——toObject<T>()方法仅用于解析单个对象(对应Map<String, dynamic>类型),无法直接处理数组,因此出现类型不匹配错误。
解决方案
修改响应处理类中的解析逻辑,遍历数组中的每个元素,逐个解析为BottomNavListItem对象,再收集为列表:
修改后的响应处理代码
Future<List<BottomNavListItem>?> getFamilyStatus(String url) async { Response response; List<BottomNavListItem>? bottomNavListModel; try { response = await WebUtil.createDio().get(url); if (kDebugMode) { print(response.data.toString()); } // 替换原解析代码为以下逻辑 if (response.data is List) { bottomNavListModel = response.data.map((item) { return Mapper.fromJson(item).toObject<BottomNavListItem>(); }).toList(); } } on DioError catch (e) { // 补充你的Dio错误处理逻辑 if (kDebugMode) { print(e.toString()); } } return bottomNavListModel; }
额外检查
你的BottomNavListItem模型类的映射逻辑已经正确绑定了id和name字段,无需修改。
内容的提问来源于stack exchange,提问作者Saniyo Mathew
相关产品推荐
相关产品推荐

