Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are getter and setter needed in Dart Programming?

Tags:

flutter

dart

I used to programming in Kotlin for a long time. I'm pretty new in Dart programming.

So I wonder getter and setter are needed in Dart Programming. (In case of getter and setter has no logic, pure getter, setter)

IDE of mine is VSCode. When I tried to see where specific variable is set and got => I used "Find All References". This function shows mix of set and get. For this reason I seriously consider to make each fields setter and getter.

When I used Kotlin, the language made getter and setter automatically. And IDE provide me separated reference of get/set. For me making each getter setter is annoying process.

Is any good way to see separated reference of set/get with IDE? or is there any other reason to use getter and setter? (In case of getter and setter has no logic, pure getter, setter)

class DisplayConstant {
  double statusbarHeight = 0;
  double devicePixelRatio = 1;
}

vs

class DisplayConstant {
  double _statusbarHeight = 0;
  double _devicePixelRatio = 1;

  double get statusbarHeight => _statusbarHeight;
  set statusbarHeight(double statusbarHeight) =>
      _statusbarHeight = statusbarHeight;
  double get devicePixelRatio => _devicePixelRatio;
  set devicePixelRatio(double devicePixelRatio) =>
      _devicePixelRatio = devicePixelRatio;
}
like image 960
Bansook Nam Avatar asked Mar 04 '23 17:03

Bansook Nam


1 Answers

Using getter/setter are optionals. It could be helpful in some situations , for example when you need to add additional logic when you get the data.

class DisplayConstant {
  //make your variables private using _ at the beginning
  double _factor = 0.5;
  double _statusbarHeight = 0;
  double _devicePixelRatio = 1;

  double get statusbarHeight => _statusbarHeight * _factor;
  double get devicePixelRatio => _devicePixelRatio * _factor;
  set statusbarHeight(double statusbarHeight) => _statusbarHeight = statusbarHeight;
  set devicePixelRatio(double devicePixelRatio) =>_devicePixelRatio = devicePixelRatio;
}

Using setters and getters is transparent to the user of the class. This allows you to evolve your API over time without breaking existing users, like this:

final display = DisplayConstant();
//set your data
display.statusbarHeight = 20;
display.devicePixelRatio = 0.5;
//get your data
print(display.statusbarHeight);
print(display.devicePixelRatio);

If you don't plan on adding some logic when you get your attribute, you can avoid get/set and call the attribute directly.

You can find more info in this link: http://dartdoc.takyam.com/dart-tips/dart-tips-ep-10.html

like image 59
diegoveloper Avatar answered Mar 29 '23 17:03

diegoveloper