Cubit中类型不匹配错误:_InternalLinkedHashMap无法转为Response
错误原因与修复方案
错误根源
你遇到的类型不匹配错误,核心原因是数据类型预期与实际返回值不匹配:
- 在
ApiProvider的_request方法中,你返回的是res.data——也就是API返回的JSON已被Dio自动解析成的Map<String, dynamic>对象 - 但在
AuthCubit的signUp方法里,你强行把这个Map赋值给了Dio的Response类型变量,导致类型转换失败
修复方案(二选一)
方案一:保留完整Response对象(推荐,便于获取状态码等元信息)
1. 修改ApiProvider的_request方法
将返回res.data改为返回完整的Dio Response对象:
Future<dynamic> _request(Function request) async { try { final res = (await request()); // 返回完整Response,而非仅data字段 return res; } on DioError catch (ex) { log('Error dio _request === ${ex.response!.statusCode}'); rethrow; } }
2. 修正AuthCubit的signUp方法
由于Dio已自动解析JSON(你设置了responseType: ResponseType.json),无需再调用jsonDecode,直接使用response.data即可:
Future signUp() async { try { final Response response = await _apiService.signUp( email: state.email ?? "", password: state.password ?? "", firstName: state.firstName ?? "", lastName: state.lastName ?? "", genderUuid: state.genderUuid ?? "", ageGroupUuid: state.ageGroupUuid ?? "", countryUuid: state.countryUuid ?? "" ); // 直接转换response.data为Map,无需jsonDecode Map<String, dynamic> data = response.data as Map<String, dynamic>; if (response.statusCode == 200) { log("I am here"); // 此处可处理返回数据,如保存accessToken、userId等 } } on DioError catch (ex) { log("cubit === ${ex.response!.data.toString()}"); emit(ErrorAuthentification(ex.response!.data["statusCode"], ex.response!.data["message"])); } catch (e) { log(e.toString()); rethrow; } }
方案二:直接返回解析后的数据(简化流程)
如果不需要Response的元信息(如statusCode),可直接在API层返回解析后的Map,Cubit直接接收:
1. 保持ApiProvider和ApiService代码不变
两者已默认返回解析后的Map<String, dynamic>对象。
2. 修正AuthCubit的signUp方法
将变量类型改为Map<String, dynamic>,移除不必要的jsonDecode:
Future signUp() async { try { final Map<String, dynamic> data = await _apiService.signUp( email: state.email ?? "", password: state.password ?? "", firstName: state.firstName ?? "", lastName: state.lastName ?? "", genderUuid: state.genderUuid ?? "", ageGroupUuid: state.ageGroupUuid ?? "", countryUuid: state.countryUuid ?? "" ) as Map<String, dynamic>; log("I am here"); // 此处可处理返回数据,如success、accessToken等 } on DioError catch (ex) { log("cubit === ${ex.response!.data.toString()}"); emit(ErrorAuthentification(ex.response!.data["statusCode"], ex.response!.data["message"])); } catch (e) { log(e.toString()); rethrow; } }
内容的提问来源于stack exchange,提问作者newbiras
相关产品推荐
相关产品推荐

