Dart Getters and Setters

Understand what getters and setters are, with easy examples

1. What are Getters and Setters? (Programming Definition)

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.

2. Real-World Example of Getters and Setters

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.

3. Important Terms

4. How to Use Getters and Setters 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:

5. Why Use Getters and Setters?

6. Summary

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.