In this tutorial you will learn about the Dart Getters and Setters and its application with practical example.
Dart Getters and Setters
Getters and setters are special class methods that is used to initialize and retrieve the values of class fields respectively. The setter method is used to set or initialize respective class fields, while the getter method is used to retrieve respective class fields. All classes have default getter and setter method associated with it. However, you are free to override the default ones by implementing the getter and setter method explicitly.
Defining a getter
The getters are defined using the get keyword with no parameters and returns a value.
Syntax:-
1 2 3 |
return_type get field_name { } |
Defining a setter
The setters are defined using the set keyword with one parameter and no return value.
Syntax:-
1 2 3 |
set field_name { } |
Example:-
The following example shows how you can use getters and setters in a Dart class –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
class Employee { String empName; int empAge; int empSalary; String get emp_name { return empName; } void set emp_name(String name) { this.empName = name; } void set emp_age(int age) { if(age<= 18) { print("Employee Age should be greater than 18 Years."); } else { this.empAge = age; } } int get emp_age { return empAge; } void set emp_salary(int salary) { if(salary<= 0) { print("Salary should be greater than 0"); } else { this.empSalary = salary; } } int get emp_salary { return empSalary; } } void main() { Employee emp = new Employee(); emp.emp_name = 'John'; emp.emp_age = 25; emp.emp_salary = 25000; print("W3Adda - Dart Getters and Setters Example."); print("Employee's Name Is : ${emp.emp_name}"); print("Employee's Age Is : ${emp.emp_age}"); print("Employee's Salary Is : ${emp.emp_salary}"); } |
Output:-