On this page10 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Getters: Calculated Fields
  4. 2. Setters: Assignments That Check
  5. 3. Getter or Method?
  6. Code Examples
  7. Common Beginner Mistakes
  8. Practice Questions
  9. Practice Answers
  10. Key Takeaways

Lecture 035: Getters & Setters

Day12: Singleton, Getters & Static
Lecture035 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

A rectangle's area isn't stored anywhere; it's worked out from the width and height. A getter looks like a field but calculates its value on the spot. A setter looks like assigning to a field, but runs code first, so it can reject bad values.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 030–033 (classes, constructors and this).


Learning Objectives

  • Write a getter with get
  • Use getters for values calculated from other fields
  • Write a setter with set that checks values
  • Pair a private field with a getter and setter
  • Know when to use a getter instead of a method

1. Getters: Calculated Fields

dart
class Rectangle {
  double width;
  double height;
  Rectangle(this.width, this.height);

  double get area => width * height;
  double get perimeter => 2 * (width + height);
  bool get isSquare => width == height;
}

var r = Rectangle(3, 4);
print(r.area);        // 12.0 (no brackets)
print(r.perimeter);   // 14.0
print(r.isSquare);    // false

r.width = 4;
print(r.area);        // 16.0 (always up to date)
print(r.isSquare);    // true

double get area => ... defines a getter: a return type, the word get, a name, and no brackets. You read it like a field (r.area), but it's recalculated each time, so it can never be out of date.

2. Setters: Assignments That Check

A setter runs when you assign to the name. Pair it with a private field (starting with _) that holds the real value:

dart
class Temperature {
  double _celsius = 0;

  double get celsius => _celsius;

  set celsius(double value) {
    if (value < -273.15) {
      print('Below absolute zero, ignored: $value');
      return;
    }
    _celsius = value;
  }

  double get fahrenheit => _celsius * 9 / 5 + 32;
  set fahrenheit(double f) => celsius = (f - 32) * 5 / 9;
}

var t = Temperature();
t.celsius = 25;          // runs the setter
print(t.fahrenheit);     // 77.0
t.fahrenheit = 212;      // converts, then uses the celsius setter
print(t.celsius);        // 100.0
t.celsius = -300;        // Below absolute zero, ignored: -300.0
print(t.celsius);        // 100.0 (unchanged)

A setter has the word set, a name and exactly one parameter. It never returns a value.

3. Getter or Method?

Use a getter when…Use a method when…
it's a property of the object (area, isEmpty, fullName)it does something (save, send, calculate with arguments)
it's quick to work outit's slow or has side effects
it needs no argumentsit needs arguments

You've used built-in getters all along: list.length, text.isEmpty, list.first.


Code Examples

Example 1: A Password Field

dart
class Password {
  String _value = '';

  set value(String text) {
    if (text.length < 8) {
      print('Rejected: "$text" is too short');
      return;
    }
    _value = text;
    print('Password set');
  }

  int get length => _value.length;
  bool get isSet => _value.isNotEmpty;
  String get masked => '*' * _value.length;
  String get strength {
    if (_value.length >= 12) return 'strong';
    if (_value.length >= 8) return 'okay';
    return 'none';
  }
}

void main() {
  var p = Password();
  print('Set? ${p.isSet}');
  p.value = 'abc';
  p.value = 'dart2026rocks';
  print('Set? ${p.isSet}, length ${p.length}, ${p.masked}, ${p.strength}');
}

Output

code
Set? false
Rejected: "abc" is too short
Password set
Set? true, length 13, *************, strong

There's a setter for value but no getter, so outside code can set a password but never read it back. Only safe things (length, masked, strength) are exposed. A getter can have a full { } body too, like strength.


Common Beginner Mistakes

1. Calling a getter with brackets

dart
print(r.area());
code
Error: 'area' isn't a function or method and can't be invoked.

Getters are read like fields: r.area.

2. Assigning to a getter with no setter

dart
r.area = 10;
code
Error: The setter 'area' isn't defined for the type 'Rectangle'.

area is calculated, so it can't be set.

3. A getter that returns itself

dart
class Person {
  int _age = 0;
  int get age => age;
}
code
Unhandled exception:
Stack Overflow

age calls the age getter, which calls age, and so on forever. Return the private field: int get age => _age;.

4. Getters and setters that check nothing: int get x => _x; set x(int v) => _x = v; adds code but no protection. Use a plain public field unless you need a rule or a calculation.


Practice Questions

  1. Write a getter fullName for a class with firstName and lastName.
  2. How do you read a getter called total?
  3. Write a setter for _quantity that ignores values below 1.
  4. Why doesn't r.area = 10 work for the Rectangle class?
  5. Getter or method: isEmpty? sendEmail(to)?

Practice Answers

  1. String get fullName => '$firstName $lastName';
  2. obj.total, without brackets.
dart
set quantity(int value) {
  if (value < 1) return;
  _quantity = value;
}
  1. area has a getter but no setter.
  2. isEmpty → getter; sendEmail(to) → method.

Key Takeaways

  • Type get name => ... is a getter: read like a field, calculated each time.
  • set name(Type value) { ... } is a setter: runs on assignment and can reject bad values.
  • Pair them with a private _field that stores the real value.
  • No setter = read-only from outside.
  • A getter must return the private field, never call itself.