It is used to retrieve a particular class field and save it in a variable. All classes have a default getter method but we can also create getter method as well. The getter method can be defined using the get keyword as:
return_type get field_name{ ... }
It must be noted we have to define a return type but there is no need to define parameters in the above method.
Setter Method in Dart
It is used to set the data inside a variable received from the getter method. All classes have a default setter method but but we can also create getter method as well. The setter method can be defined using the set keyword as:
set field_name{
...
}
Example: Using the Getter and Setter method in the dart program.
class Mathematics
{
int _numberOne = 0;
int _numberTwo = 0;
// Setter Funtion
void set setValueOne(int val)
{
_numberOne = val *6;
}
void set setValueTwo(int val)
{
_numberTwo= val * 6;
}
//getter function
int get getValueOne =>_numberOne;
int get getValueTwo =>_numberTwo;
}
void main()
{
var math = Mathematics();
math.setValueOne = 01;
math.setValueTwo = 20;
print("Value One is : ${math.getValueOne}");
print("Value Two is : ${math.getValueTwo}");
}
ย