DEV Community

Cover image for Dart getters and setters
Newton Munene
Newton Munene

Posted on

Dart getters and setters

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
}
Enter fullscreen mode Exit fullscreen mode

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,});
}
Enter fullscreen mode Exit fullscreen mode

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

}
Enter fullscreen mode Exit fullscreen mode

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,});
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (11)

Collapse
 
manuelgamboa profile image
Manuel Alejandro Gamboa Jimenez • Edited

You should never use this.argument (formals) in constructors, what's the point of constructor arguments if you are going to assign it directly to properties?, what you should do in most cases is to use setters to validate the data passed to constructor, if you don't validate then using constructor arguments is a waste of time and just duplicated code:

class Human {
  int _age;

  Human(int age) {
    setAge(age);
  }

  void setAge(int value) {
    //an age of 0 or less is invalid, 130 years or more is invalid
    if(value <= 0 || value >= 130) { 
      //throw error 
    }

    _age = value;
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
newtonmunene_yg profile image
Newton Munene

Hello. Thank you so much for the feedback.

I agree with you.

I wrote this quite a while back when I was just getting started with Dart and I have learnt quite a few things since then. Most of these articles are due for an update.

Collapse
 
huholoman profile image
Huholoman • Edited

This is misleading. In domain/business entities yes (or other value object from this layer), but for example when you have db entity, you dont want validate anything here. It adds duplicit valiation for data, which were already validated and when you decide to change the validation rules, you have to change it on multiple places.

Another thing is that immutability is considered as good practice (again in domain/business layer; database entities can have some data related to performance improvements for example), that means you dont have any setter methods, just copyWith method, which calls constructor.. and in this case you can have you validation logic in constructor and there is no need for even private method. Sure you can split validation to multiple methods if the logic gets bigger.

Collapse
 
bastienjs profile image
bastienJS

vehicleAge should be renamed to _vehicleAge. It does not make sense to make it public like the age property...

Collapse
 
aamendez3 profile image
aamendez3

This is SUPER helpful, thank you. UwU...

Collapse
 
newtonmunene_yg profile image
Newton Munene

Thank you for the notice. I'll be updating the post soon.

Collapse
 
nigel447 profile image
nigel447

int get age => vehicleAge;

Collapse
 
huholoman profile image
Huholoman • Edited

You probably want to prefix class properties with underscore as it makes them private - as this is the reason why you add getters in the first place.

Collapse
 
parsagachkar profile image
Parsa Gachkar

What about Async Getters and Setters

Collapse
 
moseskarunia profile image
Moses Karunia

why not async function instead?