In Dart, a setter is a special type of function that is used to set the value of a property on an object. Setters are defined using the
set
keyword followed by the name of the property that the setter is associated with.
To set the property, we simply assign a value to it as if it were a regular property. The setter function is automatically called with the value
that we assign to the property.
Functions declared with the set
keyword can’t return any value, so setting any return type other than void
is a
compile-time error. While this is possible to still add void
return type it is redundant and should be omitted.
class Person {
String name;
int birthYear;
Person(this.name, this.birthYear);
// Adding a calculated property age
int get age => currentYear - birthYear;
void set age(int value) => birthYear = currentYear - value; // Noncompliant
}
class Person {
String name;
int birthYear;
Person(this.name, this.birthYear);
// Adding a calculated property age
int get age => currentYear - birthYear;
set age(int value) => birthYear = currentYear - value;
}