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.
Explanation:
Private Fields:
_name
and_age
are private fields (because they start with an underscore_
). They cannot be accessed directly from outside the class.
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
.
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.
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.
- The getter
Display Method:
displayInfo()
prints thename
andage
of the person object, using the current values stored in the private fields.
Output:
Summary:
- Getters allow you to retrieve the value of private fields, and they are accessed just like regular fields.
- Setters allow you to modify the value of private fields, but you can also add validation logic or transformations.
- Getters and setters provide controlled access to an object’s properties, helping with encapsulation, validation, and maintaining the integrity of the object's state.
- They help ensure that the data in your class remains consistent and that invalid or unwanted values are not assigned directly to fields.