set variable with conditions in dart

4k Views Asked by At

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?

2

There are 2 best solutions below

2
Ben Konyi On BEST ANSWER

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 
}
0
Arhaam Patvi On
  1. For auto increment:
    Look into Timer which will allow you to automatically increment hour after a defined Duration
    https://fluttermaster.com/tips-to-use-timer-in-dart-and-flutter/
  2. For adding conditions to your increment:
    If you don't want to keep calling a function in order to increment your hour variable, you will have to add some sort of listener to the hour variable, have a look at the following package:

    property_change_notifier : https://pub.dev/packages/property_change_notifier

    Adding a listener to hour will help you define a function like your addHour() function which will automatically be called when the value of hour is changed.

    OR You could add the conditions for increment within the Timer itself.