我上课
class Job {
String id;
String jobTitle;
String updatedAt;
String createdAt;
Job(
{this.id,
this.jobTitle,
this.updatedAt,
this.createdAt});
factory Job.fromMap(Map data) {
return Job(
id: data['id'],
jobTitle: data['jobTitle'],
updatedAt: data['updatedAt'],
createdAt: data['createdAt'],
);
}
}
分配值后:
Job _job = new Job();
例如_job.jobTitle = 'farmer';
在保存到后端之前,我要确保_job对象中没有空值。
而不是检查对象类中的每个项目,例如
If(_job.jobTitle != null && _job.updatedAt != null && ....){
}
如何单步检查对象类是否包含任何空值? 像
if(_job.contains(null)){
}
答案 0 :(得分:1)
您可以创建另一种方法来检查是否有任何字段为null
:
class Job {
String id;
String jobTitle;
String updatedAt;
String createdAt;
Job({this.id, this.jobTitle, this.updatedAt, this.createdAt});
factory Job.fromMap(Map data) {
return Job(
id: data['id'],
jobTitle: data['jobTitle'],
updatedAt: data['updatedAt'],
createdAt: data['createdAt'],
);
}
bool checkIfAnyIsNull() {
return [id, jobTitle, updatedAt, createdAt].contains(null);
}
}
void main() {
Job _job = Job();
// Comment any of these fields and you would get [true].
// [false] means all fields are set.
_job.id = "1";
_job.jobTitle = "Developer";
_job.createdAt = "27-11-2019";
_job.updatedAt = "28-11-2019";
if(_job.checkIfAnyIsNull()){
print("Not all fields are set");
}
}
答案 1 :(得分:0)
最好的方法是为对象分配一个空值
_job = null ;
,然后添加新的详细信息