CodeBlanks Logo Icon CodeBlanks

Getters and setters

Learn controlled access with get and set.

get and set

Dart offers getters and setters for controlled access to private fields. They are written with the get and set keywords; the call uses no parentheses.

Example: double get balance => _balance; set balance(double value) { if (value < 0) return; _balance = value; }. Here balance is a readable and writable accessor. Reading looks like a.balance and writing like a.balance = 100. The condition inside the setter blocks negative values. This shape is a clean way to add validation without exposing the field directly.

Validation with a setter

A setter intercepts writes; this lets you validate values. When an invalid value is given, the assignment is blocked or corrected.

Example: set balance(double value) { if (value < 0) return; _balance = value; }. Here, if a negative value is given, return stops the operation and _balance stays unchanged. This prevents user mistakes; the object stays consistent. Read only fields have no setter; the field then becomes read only and cannot be changed from outside.

Practice Add a getter and setter to Account

Define the Account class; add a private double _balance field and an Account(this._balance) constructor. Write a double get balance => _balance; getter and a set balance(double value) { if (value < 0) return; _balance = value; } setter. In main, create an instance with var a = Account(100);, print with print(a.balance), update with a.balance = 200 and print again with print(a.balance).

Starter code

main.dart
// Define the Account class
// Add private _balance, constructor, getter and setter

void main() {
  // Create an Account(100) instance, print balance, update to 200, print again
}

Sample solution

main.dart
// Define the Account class
class Account {
  double _balance;
  Account(this._balance);
  double get balance => _balance;
  set balance(double value) {
    if (value < 0) return;
    _balance = value;
  }
}

void main() {
  var a = Account(100);
  print(a.balance);
  a.balance = 200;
  print(a.balance);
}

Expected output

100.0
200.0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the getter declaration

Question
  double ____ balance => _balance;
Answer
  double get balance => _balance;

Explanation: The get keyword defines a read accessor.

2 What does set balance(double value) do?

  • Only reads the value
  • Defines a static field
  • Wraps the write with validation Correct answer
  • Calls the constructor

Explanation: A setter intercepts writes and adds validation.

3 Match the accessor parts

Term Meaning
get Read accessor
set Write accessor
_balance Private field

All lessons in Intermediate