Getter and Setter in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

Reading and writing access to objects is very important in any programming language. Getter and Setter are the exact methods that we use when we want to access the reading and writing privileges to an object's properties.

Syntax

A getter usually looks something like this -

returnType get fieldName {
   // return the value
}

The returnType is the type of data we are returning. The get keyword is what tells us and the compiler that is a getter, and then lastly we have the fieldName whose value we are trying to get.

A setter usually looks something like this −

set fieldName {
   // set the value
}

The set is the keyword that tells us and the compiler that this is a setter method. After the set keyword, we have the fieldName whose value we are trying to set in the following code block.

Now, let's create a class named Employee in which we will have different fields to apply our getter and setter methods to.

Example

Consider the example shown below −

 Live Demo

class Employee {
   var empName = "mukul";
   var empAge = 24;
   var empSalary = 500;
   String get employeeName {
      return empName;
   }
   void set employeeName(String name) {
      this.empName = name;
   }
   void set employeeAge(int age) {
      if(age<= 18) {
         print("Employee Age should be greater than 18 Years.");
      } else {
         this.empAge = age;
      }
   }
   int get employeeAge {
      return empAge;
   }
   void set employeeSalary(int salary) {
      if(salary<= 0) {
         print("Salary cannot be less than 0");
      } else {
         this.empSalary = salary;
      }
   }
   int get employeeSalary {
      return empSalary;
   }
}
void main() {
   Employee emp = new Employee();
   emp.employeeName = 'Rahul';
   emp.employeeAge = 25;
   emp.employeeSalary = 2000;
   print("Employee's Name is : ${emp.employeeName}");
   print("Employee's Age is : ${emp.employeeAge}");
   print("Employee's Salary is : ${emp.employeeSalary}");
}

In the above example, we have an Employee class and when we are creating an object of the Employee class inside the main function, we are then making use of different getter and setter methods to access and write to the object's fields.

Output

Employee's Name is : Rahul
Employee's Age is : 25
Employee's Salary is : 2000
raja
Published on 21-May-2021 12:48:17
Advertisements