Custom Getters and Setters

Pre-calculation example

void main() {
  
  
  // Custom  Getters & Setters



  var employee1 = Employee(); // Creating employee1 object
  
 
  employee1.id =1;
  employee1.name ="John Doe";
  employee1.position ="CTO";
  employee1.empsalary = 30; // Calling the custom setter method 
  
  
  
  
  print(employee1.empsalary); // Calling the custom getter method 
  
  
}

class Employee {
  int id;

  String name;

  String position;
   
  int salary ; 

  
  
 // You can remove the return type from setter method
   void set empsalary(int dayworked) {
    
      this.salary = dayworked*20;    
  }
  
  
  
  int get empsalary{
  
    return this.salary; 
  
  }
  
  
  
  
  
  
}


I mentioned you can remove the return type from setter method without any problem, but

you can actually also remove return type from getter method also without any problem . Dart compiler can assume the return type

Pre checking example

circle-info

You can also use custom getters and setters as an "alias" for the original instance variables.

Last updated