Dart Getters and Setters
Getters and setters are the special class method that is used to read and write access to an object’s properties. The getter method is used to reads the value of the variable or retrieve the value and setter method is used to set or initialize respective class fields. By default, all classes are associated with getter and setter method. However, we can override the default methods by defining getter and setter method explicitly.
Defining a getter
We can define the getters method by using the get keyword with no parameter a valid return type.
Syntax:
Defining a setter
We can declare the setter method using the set keyword with one parameter and without return type.
Syntax:
Example:
Output
Student name is: John Student age is: 24 Student Branch is: Computer Science
We can also place the getter and setter method just after the. Now, let’s understand the following example:
Example – 2
Output
The car company is: Honda 20/03/2010 The modelname is: City The color is: White 10
Explanation:
In the above code, we defined the getter and setter methods before the constructor.