My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Dart getters and setters

Dart getters and setters

Newton Munene's photo
Newton Munene
·Jun 5, 2019

Prerequisites

You will need basic knowledge of

  1. Dart
  2. Object-Oriented Programming

Getters and setters are special methods that provide read and write access to an object’s properties. Each instance variable of your class has an implicit getter, and a setter if needed. In dart, you can take this even further by implementing your own getters and setters. If you've had any experience in Object-Oriented Programming you'll feel right at home. Let's get started.

In OOP a class acts as an Abstract Data Type(ADT) for an instance of that class(Object). In dart, this is also the case. The basic syntax for a class is:

class className {
 fields;
 getters/setters
 constructor
 methods/functions
}

The getters and setters can also be placed after the constructor. Now let's create a class and instantiate it.

class Vehicle {
  String make;
  String model;
  int manufactureYear;
  int vehicleAge;
  String color;

  int get age {
    return vehicleAge;
  }

  void set age(int currentYear) {
    vehicleAge = currentYear - manufactureYear;
  }

  // We can also eliminate the setter and just use a getter.
  //int get age {
  //  return DateTime.now().year - manufactureYear;
  //}

  Vehicle({this.make,this.model,this.manufactureYear,this.color,});
}

Age here is both a getter and a setter. Let's see how we can use it.

void main() {
 Vehicle car = 
 Vehicle(make:"Honda",model:"Civic",manufactureYear:2010,color:"red");
  print(car.make); // output - Honda
  print(car.model); // output - Civic
  car.age = 2019;
  print(car.age); // output - 9

}

One of my favourite ways of using getters is getting a Map from an object.

void main() {
 Vehicle car = Vehicle(make:"Honda",model:"Civic",manufactureYear:2010,color:"red");
  print(car.map); // output - {make: Honda, model: Civic, manufactureYear: 2010, color: red}
}
class Vehicle {
  String make;
  String model;
  int manufactureYear;
  int vehicleAge;
  String color;



  Map<String,dynamic> get map {
    return {
      "make": make,
      "model": model,
      "manufactureYear":manufactureYear,
      "color": color,
    };
  }

  int get age {
    return DateTime.now().year - manufactureYear;
  }

  void set age(int currentYear) {
    vehicleAge = currentYear - manufactureYear;
  }

  Vehicle({this.make,this.model,this.manufactureYear,this.color,});
}

That covers basic usage of getter and setters in Dart. There's is a lot more to learn about classes. I will cover everything in a future post. Also, note the use of named parameters in our constructors. I'll also cover those and other ways of passing parameters in a future post