Dart Getters and Setters Examples

In Object-Oriented Programming, getters and setters are special methods that provide access to an object’s properties.

Each property has its implicit getters and setters. You can create your own getters and setters if needed.

class Sale {
  final int id;
  final String name;
  final String status;
  double amount;

  double get exchangedAmount{
    return amount*1.2;
  set exchangedAmount(double rate){
    amount = amount*rate;

  String get statusText {
    Map<String, String> map = {
      'draft': 'Draft',
      'sent': 'Sent',
      'sale': 'Sale',
    if (map.containsKey(status)) {
      return map[status];
    return status;

  Sale(this.id, this.name, this.status, this.amount);
class Person {
  String _name;

  String get name => _name;

  set name(String value) => _name = value;

void main() {
  var person = Person();
  person.name = "John";
  print(person.name); // Output: John
class BankAccount {
  num _balance;


  num get balance => _balance;

  set balance(num value) {
    if (value < 0) {
      throw "Balance cannot be negative";
    _balance = value;

void main() {
  var account = BankAccount(1000);
  account.balance = 500;
  print(account.balance); // Output: 500
  account.balance = -500; // Throws an exception

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.