Flutter类型转换异常求助:_InternalLinkedHashMap无法转为String
Flutter类型转换异常排查:_InternalLinkedHashMap<String, dynamic> 不是 String 的子类型
异常信息
2023-01-04 15:05:33.297 15984-16060/com.example.food_app E/flutter: [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' #0 PopularProductController.getPopularProductList (package:food_app/controllers/popular_product_controller.dart:30:71) <asynchronous suspension> #1 _SplashScreenState._loadResource (package:food_app/pages/splash/splash_page.dart:25:5) <asynchronous suspension>
问题代码位置
popular_product_controller.dart:30:71
Future<void> getPopularProductList()async { Response response = await popularProductsRepo.getPopularProductList(); if(response.statusCode==200) { _popularProductList =[]; _popularProductList.addAll(Product.fromJson(jsonDecode(response.body)).products); _isloaded=true; update(); }else{ } }
splash_page.dart:25:5
Future<void>_loadResource() async { await Get.find<PopularProductController>().getPopularProductList(); await Get.find<RecommendedProductController>().getRecommendedProductList(); }
异常原因
错误核心是传入jsonDecode()的参数类型不匹配:jsonDecode()要求输入为String类型,但当前传入的response.body已经是解析后的_InternalLinkedHashMap<String, dynamic>(即Map类型),导致类型转换失败。
常见触发场景:
popularProductsRepo.getPopularProductList()方法内部已对接口响应体做了jsonDecode处理,返回的Response对象中body字段直接是Map类型- 误将Map类型对象传入需要String参数的
jsonDecode()方法
解决方法
方法1:移除多余的jsonDecode()调用
如果Repo层已完成响应体解析,直接将response.body传入Product.fromJson:
// 修改前 // _popularProductList.addAll(Product.fromJson(jsonDecode(response.body)).products); // 修改后 _popularProductList.addAll(Product.fromJson(response.body).products);
方法2:确保response.body为String类型再解析
如果Repo层仅返回原始响应体字符串,先验证response.body的类型(可通过print(response.body.runtimeType)确认),确保是String后再调用jsonDecode:
final Map<String, dynamic> data = jsonDecode(response.body as String); _popularProductList.addAll(Product.fromJson(data).products);
额外建议
- 检查
Product.fromJson方法的参数定义,确认它接收Map<String, dynamic>类型(这是Dart模型类fromJson方法的标准写法) - 统一项目网络请求的解析逻辑:要么在Repo层统一处理响应体解析,要么在控制器层完成,避免重复解析或类型混淆
内容的提问来源于stack exchange,提问作者Iman Alabid
相关产品推荐
相关产品推荐

