Cambo Freelance
ទំព័រដើមសេវាកម្មអត្ថបទការបង្រៀនក្រុមវគ្គបណ្តុះបណ្តាលទំនាក់ទំនង
Cambo Freelance

Professional freelance team from Cambodia delivering technology-driven solutions with cultural insight and modern expertise.

ផ្ញើសាររបស់អ្នក

ត្រៀមចាប់ផ្តើមគម្រោងរបស់អ្នក? ទំនាក់ទំនងក្រុមរបស់យើង។

ទំនាក់ទំនង

សេវាកម្ម

  • Web & Mobile Development Services
  • Graphic Design & Branding Services

តំណភ្ជាប់មានប្រយោជន៍

  • ទំព័រដើម
  • សេវាកម្ម
  • ការសិក្សា
  • អំពីយើង
  • ទំនាក់ទំនង
  • តម្លៃ

© 2026 Cambo Freelance. រក្សាសិទ្ធិទាំងអស់។

TelegramFacebookLinkedInEmail
HomeTutorialsDartGetters and Setters in Dart
🎯Dart Tutorials

97 lessons

Beginner(35)0Complete Dart Tutorial Series — Course Index1Introduction to Dart2Installing Dart SDK3Setting Up VS Code for Dart4DartPad Online Editor5Hello World in Dart6Dart Syntax7Comments in Dart8Variables in Dart9Data Types in Dart10Strings in Dart11Numbers in Dart12Booleans in Dart13Type Conversion in Dart14Constants in Dart: final and const15User Input in Dart16Arithmetic Operators in Dart17Assignment Operators in Dart18Comparison Operators in Dart19Logical Operators in Dart20Null-Aware Operators in Dart21If Statement in Dart22If Else in Dart23Else If in Dart25Switch Statement in Dart26Ternary Operator in Dart27For Loop in Dart28While Loop in Dart29Do While Loop in Dart30Break and Continue in Dart32Nested Loops in Dart33Functions in Dart35Optional Parameters in Dart37Arrow Functions in Dart38Recursive Functions in Dart
Intermediate(34)39Lists in Dart40Sets in Dart41Maps in Dart42Collection Operations in Dart
Advanced(28)73Futures in Dart74Async and Await in Dart75Streams in Dart76
🎯

Dart Tutorials

Lesson 53 of 97

All lessons
Beginner (35)0Complete Dart Tutorial Series — Course Index1Introduction to Dart
43
Spread Operator and Collection Literals in Dart
44Collection If in Dart
45Collection For in Dart
46Null Safety in Dart
47Nullable Variables in Dart
48Null Assertion Operator in Dart
49Late Keyword in Dart
50Required Keyword in Dart
51Classes and Objects in Dart
52Constructors in Dart
53Getters and Setters in Dart
54Static Members in Dart
55Interfaces in Dart
56Polymorphism in Dart
57Inheritance in Dart
58Method Overriding in Dart
59Abstract Classes in Dart
60Abstract Classes vs Interfaces in Dart
61Mixins in Dart
62Extension Methods in Dart
63Exception Handling in Dart
64Try-Catch in Dart
65Finally Block in Dart
66Custom Exceptions in Dart
67Generics in Dart
68Typedef in Dart
69Enums in Dart
70Records in Dart
71Pattern Matching in Dart
72Cascade Notation in Dart
Stream Controllers in Dart
77Isolates in Dart
78File Operations in Dart
80JSON Parsing in Dart
82HTTP Requests in Dart
83REST API Client in Dart
84Dart Packages and pub.dev
85Testing in Dart
86Dart CLI Applications
87Dart Code Style and Best Practices
88Server-side Dart with Shelf
89Introduction to Flutter
90Flutter Widgets and Layouts
91Flutter State Management
92Flutter Navigation and Routing
93Project: Calculator in Dart
94Project: Temperature Converter in Dart
95Project: Age Calculator in Dart
96Project: Todo CLI App in Dart
97Project: Student Management System in Dart
98Project: Expense Tracker in Dart
100Project: Banking System in Dart
101Project: Inventory Management System in Dart
102Project: Contact Manager in Dart
103Project: Mini REST API Backend in Dart
2
Installing Dart SDK
3Setting Up VS Code for Dart
4DartPad Online Editor
5Hello World in Dart
6Dart Syntax
7Comments in Dart
8Variables in Dart
9Data Types in Dart
10Strings in Dart
11Numbers in Dart
12Booleans in Dart
13Type Conversion in Dart
14Constants in Dart: final and const
15User Input in Dart
16Arithmetic Operators in Dart
17Assignment Operators in Dart
18Comparison Operators in Dart
19Logical Operators in Dart
20Null-Aware Operators in Dart
21If Statement in Dart
22If Else in Dart
23Else If in Dart
25Switch Statement in Dart
26Ternary Operator in Dart
27For Loop in Dart
28While Loop in Dart
29Do While Loop in Dart
30Break and Continue in Dart
32Nested Loops in Dart
33Functions in Dart
35Optional Parameters in Dart
37Arrow Functions in Dart
38Recursive Functions in Dart
Intermediate (34)39Lists in Dart40Sets in Dart41Maps in Dart42Collection Operations in Dart43Spread Operator and Collection Literals in Dart44Collection If in Dart45Collection For in Dart46Null Safety in Dart47Nullable Variables in Dart48Null Assertion Operator in Dart49Late Keyword in Dart50Required Keyword in Dart51Classes and Objects in Dart52Constructors in Dart53Getters and Setters in Dart54Static Members in Dart55Interfaces in Dart56Polymorphism in Dart57Inheritance in Dart58Method Overriding in Dart59Abstract Classes in Dart60Abstract Classes vs Interfaces in Dart61Mixins in Dart62Extension Methods in Dart63Exception Handling in Dart64Try-Catch in Dart65Finally Block in Dart66Custom Exceptions in Dart67Generics in Dart68Typedef in Dart69Enums in Dart70Records in Dart71Pattern Matching in Dart72Cascade Notation in Dart
Advanced (28)73Futures in Dart74Async and Await in Dart75Streams in Dart76Stream Controllers in Dart77Isolates in Dart78File Operations in Dart80JSON Parsing in Dart82HTTP Requests in Dart83REST API Client in Dart84Dart Packages and pub.dev85Testing in Dart86Dart CLI Applications87Dart Code Style and Best Practices88Server-side Dart with Shelf89Introduction to Flutter90Flutter Widgets and Layouts91Flutter State Management92Flutter Navigation and Routing93Project: Calculator in Dart94Project: Temperature Converter in Dart95Project: Age Calculator in Dart96Project: Todo CLI App in Dart97Project: Student Management System in Dart98Project: Expense Tracker in Dart100Project: Banking System in Dart101Project: Inventory Management System in Dart102Project: Contact Manager in Dart103Project: Mini REST API Backend in Dart
🎯DartIntermediateLesson 53 of 97Dart TeamJune 19, 2026

Getters and Setters in Dart

Learn Dart getters and setters — computed properties, validated setters, private backing fields, and encapsulation patterns for clean OOP design.


Table of Contents

  1. What are Getters and Setters?
  2. Defining a Getter
  3. Defining a Setter
  4. Computed Properties
  5. Encapsulation with Private Fields
  6. Full Example
  7. Exercise
  8. Quiz
  9. Summary

What are Getters and Setters?

Getters and setters are special methods that allow you to read and write the value of a property. They look like property accesses to the caller but execute method logic behind the scenes. This is how Dart implements encapsulation — hiding internal implementation details while providing controlled access.

Defining a Getter

A getter uses the get keyword and has no parameter list:

class Circle {
  double radius;
  Circle(this.radius);

  // Getter: computed from radius
  double get diameter => radius * 2;
  double get area => 3.14159 * radius * radius;
  double get circumference => 2 * 3.14159 * radius;
}

void main() {
  var c = Circle(5.0);
  print(c.diameter);       // 10.0
  print(c.area.toStringAsFixed(2));          // 78.54
  print(c.circumference.toStringAsFixed(2)); // 31.42
}

Defining a Setter

A setter uses the set keyword and accepts exactly one parameter. It allows validation before assigning a value:

class Temperature {
  double _celsius = 0.0;  // private backing field

  // Getter
  double get celsius => _celsius;

  // Setter — validates before assigning
  set celsius(double value) {
    if (value < -273.15) {
      throw ArgumentError(''Temperature below absolute zero: $value'');
    }
    _celsius = value;
  }

  // Computed getters for other units
  double get fahrenheit => _celsius * 9 / 5 + 32;
  double get kelvin => _celsius + 273.15;
}

void main() {
  var temp = Temperature();
  temp.celsius = 100;         // uses setter
  print(temp.fahrenheit);     // 212.0
  print(temp.kelvin);         // 373.15

  try {
    temp.celsius = -300;      // throws ArgumentError
  } on ArgumentError catch (e) {
    print(e.message);
  }
}
Output:
212.0
373.15
Temperature below absolute zero: -300.0

Computed Properties

Getters excel at computed properties — values derived from other fields. They update automatically when the underlying data changes:

class ShoppingCart {
  final List<double> _prices = [];

  void addItem(double price) => _prices.add(price);
  void removeItem(double price) => _prices.remove(price);

  double get subtotal => _prices.fold(0.0, (sum, p) => sum + p);
  double get tax => subtotal * 0.08;
  double get total => subtotal + tax;
  int get itemCount => _prices.length;
  bool get isEmpty => _prices.isEmpty;
}

void main() {
  var cart = ShoppingCart();
  cart.addItem(29.99);
  cart.addItem(14.99);
  cart.addItem(4.99);

  print(''Items: \$${cart.itemCount}'');
  print(''Subtotal: \$\$${cart.subtotal.toStringAsFixed(2)}'');
  print(''Tax: \$\$${cart.tax.toStringAsFixed(2)}'');
  print(''Total: \$\$${cart.total.toStringAsFixed(2)}'');
}

Encapsulation with Private Fields

In Dart, fields starting with _ are private to the library file. Getters and setters provide controlled public access:

class BankAccount {
  String _owner;
  double _balance;

  BankAccount(this._owner, double initialBalance)
      : _balance = initialBalance >= 0 ? initialBalance : 0;

  String get owner => _owner;
  double get balance => _balance;  // read-only — no setter

  void deposit(double amount) {
    if (amount <= 0) throw ArgumentError(''Deposit must be positive'');
    _balance += amount;
  }

  void withdraw(double amount) {
    if (amount <= 0) throw ArgumentError(''Withdrawal must be positive'');
    if (amount > _balance) throw StateError(''Insufficient funds'');
    _balance -= amount;
  }
}

void main() {
  var account = BankAccount(''Alice'', 1000.0);
  print(account.balance);  // 1000.0
  account.deposit(500);
  print(account.balance);  // 1500.0
  // account._balance = 999999;  // ERROR: private field
}

Full Example: Product Inventory

class Product {
  final String id;
  String _name;
  double _price;
  int _stock;

  Product({required this.id, required String name, required double price, int stock = 0})
      : _name = name, _price = price, _stock = stock;

  String get name => _name;
  set name(String value) {
    if (value.trim().isEmpty) throw ArgumentError(''Name cannot be blank'');
    _name = value.trim();
  }

  double get price => _price;
  set price(double value) {
    if (value < 0) throw ArgumentError(''Price cannot be negative'');
    _price = value;
  }

  int get stock => _stock;
  bool get inStock => _stock > 0;
  bool get lowStock => _stock > 0 && _stock <= 5;

  void restock(int units) {
    if (units <= 0) throw ArgumentError(''Units must be positive'');
    _stock += units;
  }

  bool sell(int units) {
    if (units > _stock) return false;
    _stock -= units;
    return true;
  }

  @override
  String toString() => ''Product($id, $_name, \$\$${_price.toStringAsFixed(2)}, stock=$_stock)'';
}

void main() {
  var p = Product(id: ''P001'', name: ''Dart Book'', price: 39.99, stock: 10);
  print(p);
  p.sell(3);
  print(''In stock: \$${p.inStock}, Low stock: \$${p.lowStock}'');
  p.price = 34.99;
  print(p);
}
Output:
Product(P001, Dart Book, $39.99, stock=10)
In stock: true, Low stock: false
Product(P001, Dart Book, $34.99, stock=7)

Exercise

  1. Create a Rectangle class with private _width and _height fields, validated setters (must be positive), and getters for area, perimeter, and isSquare.
  2. Create a Password class with a setter that requires at least 8 characters, one digit, and one uppercase letter. The getter should return the hashed version (simulate with reversed string).

Quiz

1. What keyword defines a getter in Dart?

  • A) property
  • B) get ✅
  • C) read
  • D) accessor

2. Can a Dart getter have parameters?

  • A) Yes, any number
  • B) Yes, exactly one
  • C) No, getters take no parameters ✅
  • D) Only optional parameters

3. What is the main benefit of a setter over direct field assignment?

  • A) Faster performance
  • B) Validation and encapsulation — logic runs before the value is stored ✅
  • C) Automatic type conversion
  • D) Thread safety

Summary

Getters (get) and setters (set) provide controlled property access in Dart. Define getters for computed properties that derive from other fields. Use setters to validate input before assigning to private backing fields. Fields prefixed with _ are private to the library file, enforcing encapsulation. Callers access getters and setters exactly like regular fields — the logic is transparent.

dartprogrammingintermediateoop
PreviousLesson 52: Constructors in DartNextLesson 54: Static Members in Dart
Back to All Tutorials