null check cant get out of this

guys ı cant get out of this .can you check and infor me about the place where ı should put null check .
this for sharing the post for formality.ı didnt wanna determine the name age and salaray below.

class _Employee {
  String? empName;
  int? empAge;
  int? empSalary;

  String get employeeName {
    return empName!;
  }

  void set employeeName(String name) {
    this.empName = name;
  }

  void set employeeAge(int age) {
    if (age == null) {
      print("please give a number");
    } else if (age <= 18) {
      print("please give a value number");

      this.empAge = age;
    }
  }

  int get employeeAge {
    return empAge!;
  }

  void set employeeSalary(int salary) {
    salary <= 0
        ? print("Salary cannot be less than 0")
        : this.empSalary = salary;
  }

  int get employeeSalary {
    return empSalary!;
  }
}

void main() {
  _Employee emp = _Employee();
  emp.employeeName;
  emp.employeeAge;
  emp.employeeSalary;
  print("Employee's Name is : ${emp.employeeName}");
  print("Employee's Age is : ${emp.employeeAge}");
  print("Employee's Salary is : ${emp.employeeSalary}");
}

>Solution :

You can change the return dataType to nullable, instead of focing with null-assert!.

 String? get employeeName {
    return empName;
  }

Or you can return default value on null case.

 String get employeeName {
    return empName ?? "Got null on empName";
  }

You need to set value like

emp.employeeName = "Test";

Full snippet can be


class _Employee {
  String? empName;
  int? empAge;
  int? empSalary;

  String get employeeName {
    return empName ?? "Got null on empName";
  }

  set employeeName(String name) {
    empName = name;
  }

  set employeeAge(int? age) {
    if (age == null) {
      print("please give a number");
    } else if (age <= 18) {
      print("please give a value number");

      empAge = age;
    }
  }

  int get employeeAge {
    return empAge ?? 0;
  }

  set employeeSalary(int salary) {
    salary <= 0 ? print("Salary cannot be less than 0") : empSalary = salary;
  }

  int get employeeSalary {
    return empSalary ?? 0;
  }
}

void main() {
  _Employee emp = _Employee();
  emp.employeeName = "Test";
  emp.employeeAge = 12;
  emp.employeeSalary;
  print("Employee's Name is : ${emp.employeeName}");
  print("Employee's Age is : ${emp.employeeAge}");
  print("Employee's Salary is : ${emp.employeeSalary}");
}

Find more on dart.dev/guides/language/language-tour

Leave a Reply