0

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
  • You want to have a functionality in your class without having a function?
    – J. S.
    Feb 4, 2020 at 16:15
  • yes if possible
    – prg.dev
    Feb 7, 2020 at 10:12

2 Answers 2

3

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 
}
2
  • it give this error ``` Named optional parameters can't start with an underscore ```
    – prg.dev
    Feb 6, 2020 at 17:59
  • 1
    Ah shoot, that's right. I've edited the answer to fix the answer.
    – Ben Konyi
    Feb 6, 2020 at 19:43
0
  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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.