Reputation: 2902
I have a class
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'],
);
}
}
After assigning values:
Job _job = new Job();
For instance _job.jobTitle = 'farmer';
Before saving to the backend, I want to make sure there are no null values within, the _job object.
Rather than checking for each item in the object class e.g
If(_job.jobTitle != null && _job.updatedAt != null && ....){
}
How can I do a one-step check if the object class contains any null values? Something like
if(_job.contains(null)){
}
Upvotes: 4
Views: 8577
Reputation: 2802
the Best Approach is to assign a null to the Object
_job = null ;
and then add the new Details
Upvotes: 0
Reputation: 6061
You can create another method to check if any of fields is 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");
}
}
Upvotes: 11