LearnToday
LearnToday

Reputation: 2902

How to check if a class contains null in Flutter

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

Answers (2)

Arun R. Prajapati
Arun R. Prajapati

Reputation: 2802

the Best Approach is to assign a null to the Object

_job = null ;

and then add the new Details

Upvotes: 0

Dinko Pehar
Dinko Pehar

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

Related Questions