Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 61 ยท Classes and Object-Oriented Dart

Getters, Setters and Properties

Learn Dart getters and setters: computed properties, validation on assignment, read-only fields, and how library-level privacy replaces private keywords.

In Dart, every instance variable you declare already comes with a getter, and a setter too unless it is final. That means person.name and person.name = 'Ada' look the same whether they touch a plain field or run code. This is why Dart programmers rarely write getName() and setName() methods: you can start with a simple public field and later swap it for a getter and setter pair without changing a single line of calling code.

In this lesson you will write your own getters and setters, build computed and validated properties, and learn how Dart's unusual privacy rule works. Dart code is read-only; the stand-ins use TypeScript's get and set accessors, which have the same shape.

Fields are properties already

Look at this class:

DART
class Account {
  String owner;
  double balance = 0;

  Account(this.owner);
}

void main() {
  var account = Account('Ada');
  account.balance = 120;          // calls the implicit setter
  print(account.balance);         // calls the implicit getter
}

The compiler behaves as if Account had a getter balance and a setter balance=. A final field gets only the getter, so it is read-only from the outside. Later, if you decide that assigning a negative balance must be rejected, you can replace the field with explicit accessors and callers will not notice.

Writing a getter

A getter is a method declared with the keyword get and no parameter list. It is used like a field, without parentheses.

DART
class Rectangle {
  final double width;
  final double height;

  const Rectangle(this.width, this.height);

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

void main() {
  var r = Rectangle(3, 4);
  print(r.area);        // 12.0
  print(r.isSquare);    // false
}

This is a computed property: area is calculated on every read, so it can never become out of date with width and height. If you stored area in a field, you would have to remember to update it whenever the sides changed. Use a getter whenever a value can be derived from other state and the calculation is cheap and has no side effects.

A getter should feel like reading a field. If it does heavy work, talks to the network or changes state, make it a method such as calculateArea() or fetchProfile() so the parentheses warn the reader.

Writing a setter

A setter uses set, takes exactly one parameter, and is used like an assignment. It is the place to validate or convert incoming values.

DART
class Thermometer {
  double _celsius = 0;

  double get celsius => _celsius;

  set celsius(double value) {
    if (value < -273.15) {
      throw ArgumentError.value(value, 'celsius', 'below absolute zero');
    }
    _celsius = value;
  }

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

void main() {
  var t = Thermometer();
  t.celsius = 25;
  print(t.fahrenheit);     // 77.0
  t.fahrenheit = 212;
  print(t.celsius);        // 100.0
}

Notice three things. The backing field _celsius is private. The getter and setter share the name celsius, and Dart treats them as one property. And fahrenheit has no backing storage at all: it is a view of _celsius in other units, and its setter routes through the celsius setter so validation applies in both directions. If you give a property a getter and a setter, the two must have the same type.

flowchart LR
    C["Caller code<br/>t.celsius = 25"] --> S["setter celsius"]
    S --> V{"valid?"}
    V -- yes --> F["private field<br/>_celsius"]
    V -- no --> E["throws ArgumentError"]
    F --> G["getter celsius"]
    G --> R["Caller code<br/>print(t.celsius)"]

A setter can guard a private field; the getter exposes it back to callers.

TypeScript A validated property and a computed one (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Privacy belongs to the library

Dart has no private or public keyword. Instead, any identifier that starts with an underscore is private, and private means private to the library, which usually means the file, not the class. Code in another file cannot see _celsius, but other classes in the same file can.

DART
// file: temperature.dart
class Thermometer {
  double _celsius = 0;
}

class Calibrator {
  void zero(Thermometer t) {
    t._celsius = 0;       // allowed: same library (same file)
  }
}

That surprises people who come from Java or C#. In practice it works well: classes that cooperate live together in one file, and the file boundary is the encapsulation boundary. The rule applies to everything: fields, methods, constructors, and even top-level functions and classes. Read Libraries, Imports and Packages to see how files and libraries relate.

A common pattern is a public read-only view of private state:

DART
class Playlist {
  final List<String> _songs = [];

  List<String> get songs => List.unmodifiable(_songs);   // callers get a read-only copy
  void add(String song) => _songs.add(song);
}

If you returned _songs directly, any caller could call .clear() on it and bypass your class. Exposing an unmodifiable view keeps control where it belongs.

Static, abstract and lazy accessors

Getters and setters can also be static (static int get count => _count;), and they can be abstract in an abstract class, which forces subclasses to supply them; that comes up in Abstract Classes and Implicit Interfaces. For an expensive value that you want to compute once, on first use, use late final with an initializer:

DART
class Report {
  late final String summary = _buildSummary();   // runs once, on first read

  String _buildSummary() => 'big computation...';
}

See late Variables and Lazy Initialization for the details and the pitfalls.

TypeScript Read-only views and lazy values (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does a caller use a getter named area?

    A getter is read like a field, without parentheses. That is what lets you change a field into a getter without changing the callers.
  2. 2. What accessors does a final instance field get automatically?

    A final field is assigned once, so Dart creates only the getter. A non-final field gets both.
  3. 3. What does a leading underscore on _balance mean in Dart?

    Privacy is library-level. Other classes in the same file can access _balance, but code in other files cannot.
  4. 4. When is a computed getter a better choice than a stored field?

    A getter recalculates from the current state, so it cannot become stale. It should stay cheap and free of side effects.
  5. 5. Why return List.unmodifiable(_songs) from a getter?

    Returning the private list directly would let callers add or clear items. An unmodifiable view keeps the class in control of its state.

Summary

  • Every instance variable has an implicit getter, and a setter unless it is final.
  • Write Type get name => ...; for computed properties and set name(Type value) {...} to validate or convert on assignment.
  • Callers use properties like fields, so you can replace a field with accessors later without breaking code.
  • A name that starts with _ is private to the library, usually the file, not to the class.
  • Expose collections through unmodifiable views, and use late final for values computed once on first use.

Next, build class hierarchies with Inheritance and Polymorphism.