Dart Getter and Setter


Getters and Setters in Dart

In Dart, getters and setters are special methods that allow you to control access to an object's properties (fields).

  • Getter: A getter is a method that allows you to retrieve the value of a private field. It is accessed like a field.
  • Setter: A setter is a method that allows you to modify the value of a private field. It is called like a function but acts like a property.

Benefits of Getters and Setters:

  • Encapsulation: You can hide the internal details of how the data is stored.
  • Validation: You can add validation or transformation logic when getting or setting values.
  • Read-only or Write-only fields: You can make a property read-only (via only a getter) or write-only (via only a setter).

Syntax for Getters and Setters in Dart:

  • Getter: Type get propertyName => _property;
  • Setter: set propertyName(Type value) { _property = value; }

Example of Getters and Setters in Dart

Let’s create a class Person that demonstrates how getters and setters work.

class Person { // Private field String _name; int _age; // Constructor Person(this._name, this._age); // Getter for _name String get name => _name; // Setter for _name set name(String newName) { if (newName.isNotEmpty) { _name = newName; } else { print('Name cannot be empty'); } } // Getter for _age int get age => _age; // Setter for _age set age(int newAge) { if (newAge >= 0) { _age = newAge; } else { print('Age cannot be negative'); } } // Method to display info void displayInfo() { print('Name: $_name, Age: $_age'); } } void main() { var person = Person('Alice', 30); // Accessing public properties via getters print('Person\'s Name: ${person.name}'); // Output: Person's Name: Alice print('Person\'s Age: ${person.age}'); // Output: Person's Age: 30 // Modifying private fields using setters person.name = 'Bob'; // Output: (No error) person.age = 35; // Output: (No error) // Accessing the modified values print('Updated Name: ${person.name}'); // Output: Updated Name: Bob print('Updated Age: ${person.age}'); // Output: Updated Age: 35 // Trying to set invalid values using setters person.name = ''; // Output: Name cannot be empty person.age = -5; // Output: Age cannot be negative // Displaying info after invalid attempts person.displayInfo(); // Output: Name: Bob, Age: 35 }

Explanation:

  1. Private Fields:

    • _name and _age are private fields (because they start with an underscore _). They cannot be accessed directly from outside the class.
  2. Getters:

    • String get name => _name; is the getter for the _name field. It returns the value of the private field _name.
    • int get age => _age; is the getter for the _age field. It returns the value of the private field _age.
  3. Setters:

    • set name(String newName) {...} is the setter for the _name field. It allows setting the value of _name, but it includes a validation to ensure that the name is not empty.
    • set age(int newAge) {...} is the setter for the _age field. It allows setting the value of _age, but it ensures that the age is not negative.
  4. Accessing and Modifying Data:

    • The getter person.name retrieves the value of the private _name field.
    • The setter person.name = 'Bob'; sets the value of the private _name field with the value 'Bob'.
    • If an invalid value is provided (e.g., an empty name or a negative age), the setter prints an error message.
  5. Display Method:

    • displayInfo() prints the name and age of the person object, using the current values stored in the private fields.

Output:

Person's Name: Alice Person's Age: 30 Updated Name: Bob Updated Age: 35 Name cannot be empty Age cannot be negative Name: Bob, Age: 35

Summary:

  1. Getters allow you to retrieve the value of private fields, and they are accessed just like regular fields.
  2. Setters allow you to modify the value of private fields, but you can also add validation logic or transformations.
  3. Getters and setters provide controlled access to an object’s properties, helping with encapsulation, validation, and maintaining the integrity of the object's state.
  4. They help ensure that the data in your class remains consistent and that invalid or unwanted values are not assigned directly to fields.