Understand what getters and setters are, with easy examples
Getters and setters are special methods in Dart that allow you to read (get) or change (set) the values of private variables in a controlled way.
- A getter lets you access the value of a variable as if it were a property.
- A setter lets you update the value of a variable but with control over how it changes.
Imagine you have a treasure box that holds your favorite toys. You don’t want just anyone to take toys or put broken toys inside. So, you have a getter to look inside the box safely and a setter that checks toys before letting you put them in.
_ in Dart).class Person {
// private variable (underscore means private)
String _name;
Person(this._name);
// Getter to read _name
String get name {
return _name;
}
// Setter to change _name with control
set name(String newName) {
if (newName.isNotEmpty) {
_name = newName;
} else {
print('Name cannot be empty!');
}
}
}
void main() {
var person = Person('Alice');
// Using getter
print(person.name); // Output: Alice
// Using setter
person.name = 'Bob';
print(person.name); // Output: Bob
// Trying to set an empty name
person.name = '';
// Output: Name cannot be empty!
print(person.name); // Output: Bob (unchanged)
}
Explanation:
_name private so it can't be changed directly from outside.get name lets us read the name like a property.set name lets us update the name, but only if the new name is not empty.Getters and setters in Dart help you safely access and modify private variables, just like having special doors to your treasure box that check what goes in or out.