Flutter中Dio解析数据到Model类时Api调用错误:RegistrationResponse未注册
解决方案
这个错误的核心原因是object_mapper库要求必须先将目标模型类注册到Reflection.factories中,才能完成JSON到对象的解析。以下是具体修复步骤:
1. 让RegistrationResponse实现Mappable接口
修改你的模型类,使其继承并实现Mappable接口,完成字段映射逻辑:
import 'package:object_mapper/object_mapper.dart'; class RegistrationResponse extends Mappable { // 你的模型字段示例 String? userId; String? email; String? username; RegistrationResponse({this.userId, this.email, this.username}); // 实现Mappable的map方法,完成JSON字段到模型属性的映射 @override void map(Map map) { userId = map['userId'] as String?; email = map['email'] as String?; username = map['username'] as String?; // 按实际返回的JSON字段补充其他映射 } // 可选:如果需要将对象转为JSON,实现toMap方法 @override Map toMap() { return { 'userId': userId, 'email': email, 'username': username, }; } }
2. 注册模型类到Reflection工厂
在使用Mapper解析JSON之前,必须将RegistrationResponse的构造函数注册到Reflection.factories中。推荐在App初始化时完成注册:
void main() { // 注册所有需要映射的模型类 Reflection.factories[RegistrationResponse] = () => RegistrationResponse(); runApp(const MyApp()); }
如果不想在main中注册,也可以在调用接口的文件顶部添加注册代码,确保在解析逻辑执行前完成注册。
3. 验证解析逻辑
你的现有解析代码可以保持不变,现在应该能正常将JSON转为RegistrationResponse对象:
RegistrationResponse? user; try { Response userData = await WebUtil.createDio().post('/User', data: requestData); if (kDebugMode) { print('User Info: ${userData.data}'); } user = Mapper.fromJson(userData.data).toObject<RegistrationResponse>(); } on DioError catch (e) { // 建议添加错误日志,方便排查问题 if (kDebugMode) { print('Registration error: ${e.message}'); } }
额外注意事项
- 如果你的模型类使用带必填参数的构造函数,注册时的工厂函数需要确保能创建合法实例(通常解析场景下建议提供空构造函数,通过
map方法赋值) - 若有多个模型类需要映射,可以把所有注册逻辑放到单独的文件(比如
mapper_registrations.dart)中,统一管理
内容的提问来源于stack exchange,提问作者kapil tk
相关产品推荐
相关产品推荐

