Getters and setters are special methods in Dart that provide read and write access to an object's properties. They offer a way to control how values are retrieved and modified, allowing for data encapsulation and validation.
Getters are methods that retrieve the value of a property. They're defined using the get
keyword and don't take any parameters.
class Rectangle {
double _width, _height;
Rectangle(this._width, this._height);
double get area => _width * _height;
}
In this example, area
is a getter that calculates and returns the rectangle's area.
Setters are methods that set the value of a property. They're defined using the set
keyword and take one parameter.
class Temperature {
double _celsius = 0;
double get fahrenheit => (_celsius * 9 / 5) + 32;
set fahrenheit(double value) {
_celsius = (value - 32) * 5 / 9;
}
}
Here, the fahrenheit
setter converts the input to Celsius and stores it.
While Dart allows direct access to public properties, getters and setters provide more control. They're particularly useful when you need to:
Getters and setters are powerful tools in Dart for managing object properties. They enhance encapsulation, allow for computed properties, and provide a clean interface for interacting with objects. As you develop more complex Dart applications, mastering getters and setters will help you write more maintainable and flexible code.
To further enhance your Dart skills, explore related concepts like Dart Classes and Dart Inheritance.