如何处理Flutter 2.0 模型类中的空安全(Null Safety)问题
Flutter 2.0空安全下模型类字段可空问题解决方案
报错原因
Dart 2.12及以上版本(对应Flutter 2.0+)默认启用空安全机制,所有声明的类型默认不可为null,你当前的写法中所有字段都是非空类型,但构造函数的可选命名参数没有指定默认值也没有加required修饰,默认隐式值为null,和非空类型冲突才会触发报错。
具体处理方案
按照你说的数据库仅first_name和email为非空字段,其余字段允许为空,你可以按照以下方式修改代码:
- 给所有允许为空的字段类型后添加
?,声明为可空类型 - 仅给确定非空的
first_name、email字段添加required修饰符 - 如果你使用json_serializable序列化/反序列化,还可以给对应字段配置默认值,避免空值异常
修改后的示例代码
import 'package:json_annotation/json_annotation.dart'; part 'user.g.dart'; // 自动生成的序列化文件引用,记得补充 @JsonSerializable() class User { // 允许为空的字段声明为可空类型 int? iduser; String? uid; // 确定非空的字段保留非空类型 String first_name; String? last_name; String? profile_picture; String email; String? phone; // 如果空值时需要指定默认值,加@JsonKey注解配置 @JsonKey(defaultValue: false) bool? is_disabled; int? created_date; int? last_updated; User({ this.iduser, this.uid, required this.first_name, this.last_name, this.profile_picture, required this.email, this.phone, this.is_disabled, this.created_date, this.last_updated }); // 补充序列化/反序列化方法,配合build_runner生成对应代码 factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json); Map<String, dynamic> toJson() => _$UserToJson(this); }
额外说明
- 如果某类字段一定不会为空,只是初始化时需要传入,就加
required修饰 - 如果字段允许为空,就加
?声明为可空类型,后续使用时需要注意空安全调用(用?.、!或者提前判空处理) - 如果你需要给字段设置固定默认值,除了用
@JsonKey的defaultValue,也可以在构造函数参数里直接赋值,比如this.is_disabled = false
内容的提问来源于stack exchange,提问作者PeakGen
相关产品推荐
相关产品推荐

