What are the getter and setter methods in Dart?
The class methods , getter and setter , are used to manipulate the data of the
class attributes.A setter is used to set the data of the fieldName class to same variable , whereas
a getter is used to read or get the data of the fieldName class.
Getter method
A
getter
method is used to get and save a specificfieldName
class in a variable. A defaultgetter
method exists in all classes, but it can be overridden explicitly. Theget
keyword can be used to define thegetter
method.Syntax:
returnType get fieldName { // return the value }
Setter method
The
setter
method is used to set the data of a variable returned by the getter method. A defaultsetter
function exists in all classes, although it can be overridden explicitly.The
set
keyword can be used to define thesetter
method.Syntax :
returnType set fieldName { // set the value }
class One {
late String newName;
String get getName {
return newName;
}
set setName(String name) {
newName = name;
}
}
void main(){
One jeet = One();
jeet.setName = "Jeet";
print("Welcome to ${jeet.getName}");
}
Welcome to Jeet
Exited.