如何解决Flutter中‘type 'null' is not a subtype of type object’错误
问题分析与修复
错误原因
出现“type 'null' is not a subtype of type object”错误,核心问题有两个:
- 模型类字段映射错误
在SignUpFormModel的toJson方法中,错误地将password字段赋值给username键,同时遗漏了正确的password字段映射:
Map<String, dynamic> toJson() { return { 'name': name, 'email': email, 'username': password, // 此处映射错误,后端无法获取正确密码字段 'profile_picture': profilePicture, }; }
若后端要求password为必填非空字段,该错误会导致字段值缺失/为null,触发类型转换错误。
- 核心注册字段可能为null
SignUpFormModel中的name、email、password均为可选类型(String?),如果上游页面传递的widget.data中这些字段为null,调用toJson传递给后端时,若接口要求这些字段为非空Object类型,就会抛出null转Object的类型错误。
修复步骤
步骤1:修正字段映射
根据后端接口要求,调整toJson方法的字段对应关系,确保字段名和值匹配:
Map<String, dynamic> toJson() { return { 'name': name, 'email': email, 'password': password, // 修正为正确的密码字段映射 'profile_picture': profilePicture, // 若后端需要username字段,需在模型中添加对应字段并正确映射 }; }
步骤2:强制核心字段非空
- 修改
SignUpFormModel构造函数,将name、email、password设为必填项,编译阶段避免null值:
SignUpFormModel({ required this.name, required this.email, required this.password, this.profilePicture, });
- 若上游页面已传递非空值,可在页面的按钮点击事件中添加兜底检查:
onPressed: () { if (selectedImage == null) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: const Text('Gambar tidak boleh kosong'), backgroundColor: redColor, ), ); } else if (widget.data.name == null || widget.data.email == null || widget.data.password == null) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: const Text('注册信息不完整'), backgroundColor: redColor, ), ); } else { // 触发注册事件 context.read<AuthBloc>().add( AuthRegister( widget.data.copyWith( profilePicture: 'data:image/png;base64,${base64Encode(File(selectedImage!.path).readAsBytesSync())}', ), ), ); } }
步骤3:优化图片处理逻辑
添加异常捕获,避免图片文件损坏导致的崩溃:
try { final imageBytes = File(selectedImage!.path).readAsBytesSync(); final base64Image = base64Encode(imageBytes); context.read<AuthBloc>().add( AuthRegister( widget.data.copyWith( profilePicture: 'data:image/png;base64,$base64Image', ), ), ); } catch (e) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('图片处理失败:$e'), backgroundColor: redColor, ), ); }
内容的提问来源于stack exchange,提问作者Dimas Seto Rizky Goenardi
相关产品推荐
相关产品推荐

