set variable with conditions in dart

Issue

I have MyDateTime class and it has a variable hour. I need to set this variable with some condition when I create an object. For example, I have this object:

MyDateTime dt = MyDateTime(2020, 2, 3, 3, 2);

now I need to increment the hour i.e. dt.hour++;

my question how I can change the hour of the object without adding new functions, at the same time i need to increment the hour with condition


class MyDateTime {
  int year;
  int month;
  int day;
  int hour;
  int minute;
  int second;

  MyDateTime({this.year, this.month, this.day ,this.hour=0, this.minute=0, this.second=0});
  // this is the condition
  set addHour(int h){
    if(this.hour == 23) this.hour = 0;
    else if(this.hour == 0) this.hour = 1;
    else this.hour++;
  }



}

I don’t want to have function (ex: addHour)

Is there way to do it?

Solution

You can use a custom setter for this purpose:

class MyDateTime {
  int year;
  int month;
  int day;
  int _hour;
  int minute;
  int second;

  MyDateTime({this.year, this.month, this.day, int hour=0, this.minute=0, this.second=0}) : _hour = hour;


  // this is the condition
  set hour(int h) => _hour = h % 24;

  // We need to define a custom getter as well.
  int get hour => _hour;
}

Then you can do the following:

main() {
  final dt = MyDateTime();
  print(dt.hour); // 0
  print(++dt.hour); // 1
  dt.hour += 2;
  print(dt.hour); // 3 
}

Answered By – Ben Konyi

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

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