Getters and Setters
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 21 of 110.
Getters and setters provide a way to access and modify class fields through special methods that look like regular properties. Instead of exposing fields directly, you can control how values are read and written.
A getter is defined using the get keyword and returns a computed or stored value:
class Rectangle {
double width;
double height;
Rectangle(this.width, this.height);
double get area => width * height;
double get perimeter => 2 * (width + height);
}
Rectangle rect = Rectangle(5, 3);
print(rect.area); // 15.0
print(rect.perimeter); // 16.0Notice that area and perimeter are accessed like fields, but they're calculated each time. No parentheses needed.
A setter uses the set keyword and allows you to control how a value is assigned:
class Temperature {
double _celsius;
Temperature(this._celsius);
double get celsius => _celsius;
set celsius(double value) {
if (value >= -273.15) {
_celsius = value;
}
}
double get fahrenheit => _celsius * 9 / 5 + 32;
set fahrenheit(double value) {
celsius = (value - 32) * 5 / 9;
}
}
Temperature temp = Temperature(25);
print(temp.fahrenheit); // 77.0
temp.fahrenheit = 100;
print(temp.celsius); // 37.78The setter validates input before storing it and can even convert between units. This gives you control over your data while keeping a clean, property-like syntax for users of your class.
Challenge
EasyLet's build a score tracker for a game that uses getters and setters to manage player statistics with validation and computed values.
You'll organize your code into two files:
player.dart: Define aPlayerclass that tracks a player's game performance. Your class should have:- A
String namefield for the player's name - A private
int _scorefield starting at0 - A private
int _livesfield starting at3 - A constructor that takes the player's name
- A getter
scorethat returns the current score - A setter
scorethat only accepts values of0or greater (ignore negative values) - A getter
livesthat returns the current lives - A setter
livesthat only accepts values between0and5inclusive (ignore values outside this range) - A getter
levelthat computes the player's level based on score: score divided by100(integer division), plus1 - A getter
isAlivethat returnstrueif lives is greater than0 - A
displayStatus()method that prints the player's current status
- A
main.dart: Import your player class and demonstrate the getters and setters:- Create a player named
'Alex' - Set the score to
250and calldisplayStatus() - Try to set the score to
-50(should be ignored) and calldisplayStatus() - Set lives to
1and calldisplayStatus() - Try to set lives to
10(should be ignored) and calldisplayStatus()
- Create a player named
The displayStatus() method should print in this exact format:
[name] | Score: [score] | Level: [level] | Lives: [lives] | Alive: [isAlive]Expected output:
Alex | Score: 250 | Level: 3 | Lives: 3 | Alive: true
Alex | Score: 250 | Level: 3 | Lives: 3 | Alive: true
Alex | Score: 250 | Level: 3 | Lives: 1 | Alive: true
Alex | Score: 250 | Level: 3 | Lives: 1 | Alive: trueCheat sheet
Getters and setters provide controlled access to class fields through special methods that look like regular properties.
Getter - defined using the get keyword, returns a computed or stored value:
class Rectangle {
double width;
double height;
Rectangle(this.width, this.height);
double get area => width * height;
double get perimeter => 2 * (width + height);
}
Rectangle rect = Rectangle(5, 3);
print(rect.area); // 15.0 - accessed like a field, no parentheses
print(rect.perimeter); // 16.0Setter - uses the set keyword, controls how values are assigned:
class Temperature {
double _celsius;
Temperature(this._celsius);
double get celsius => _celsius;
set celsius(double value) {
if (value >= -273.15) {
_celsius = value;
}
}
double get fahrenheit => _celsius * 9 / 5 + 32;
set fahrenheit(double value) {
celsius = (value - 32) * 5 / 9;
}
}
Temperature temp = Temperature(25);
print(temp.fahrenheit); // 77.0
temp.fahrenheit = 100;
print(temp.celsius); // 37.78Setters can validate input and convert between units while maintaining clean, property-like syntax.
Try it yourself
import 'player.dart';
void main() {
// TODO: Create a player named 'Alex'
// TODO: Set the score to 250 and call displayStatus()
// TODO: Try to set the score to -50 (should be ignored) and call displayStatus()
// TODO: Set lives to 1 and call displayStatus()
// TODO: Try to set lives to 10 (should be ignored) and call displayStatus()
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor