📅  最后修改于: 2023-12-03 15:14:36.004000             🧑  作者: Mango
In Dart programming language, a getter is a special type of method that is used to retrieve the value of a class variable. Getters are defined using the "get" keyword followed by the name of the getter method.
The basic syntax of defining a getter in Dart is as follows:
// defining a getter
return_type get getter_name {
// code to retrieve value
}
// usage of getter
var variable_name = object_name.getter_name;
Here is a simple example of a class "Person" with a "name" variable and a getter method to retrieve it:
class Person {
String _name; // private variable
// getter to retrieve name
String get name {
return _name;
}
// setter to update name
set name(String name) {
_name = name;
}
}
void main() {
var person1 = Person();
person1.name = 'John'; // calls the setter to set name
print('Name of person1: ${person1.name}'); // calls the getter to retrieve name
}
The output of the above code will be:
Name of person1: John
Getters are used to retrieve the value of a class variable in Dart programming language. They are defined using the "get" keyword followed by the name of the getter method. Getters can be used in conjunction with setters to provide encapsulation and protection for class variables.