In Dart, getters and setters are used to control access to the properties of a class. They allow you to execute custom code when getting or setting the value of a property. Here's how you can define getters and setters in Dart:
1. Getters are methods that are used to retrieve the value of a property.
2. In Dart, getters do not require parentheses when they are accessed.
3. They are defined using the get keyword followed by the getter name.
4. Getters are typically used to provide read-only access to properties.
class MyClass {
int _value = 0; // Private variable
// Getter for accessing the value
int get value => _value;
}
void main() {
var obj = MyClass();
print(obj.value); // Accessing the getter
}
1. Setters are methods that are used to set the value of a property.
2. They are defined using the set keyword followed by the setter name.
3. Setters are typically used to provide write-only or validation logic when setting the value of properties.
class MyClass {
int _value = 0; // Private variable
// Getter for accessing the value
int get value => _value;
// Setter for setting the value
set value(int newValue) {
if (newValue >= 0) {
_value = newValue;
} else {
throw ArgumentError('Value must be non-negative.');
}
}
}
void main() {
var obj = MyClass();
obj.value = 10; // Setting the value using the setter
print(obj.value); // Accessing the value using the getter
}
Getters and setters allow you to encapsulate the internal representation of a class and provide controlled access to its properties, enabling better data integrity and encapsulation.