在飞镖中设置带有条件的变量

set variable with conditions in dart

我有 MyDateTime class 并且它有一个变量 hour。当我创建一个对象时,我需要在某些条件下设置这个变量。例如,我有这个对象:
MyDateTime dt = MyDateTime(2020, 2, 3, 3, 2);

现在我需要增加 hourdt.hour++;

我的问题是如何在不添加新函数的情况下更改对象的 hour,同时我需要使用条件

增加 hour

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++;
  }



}

我不想使用函数(例如:addHour

有办法吗?

  1. 对于自动递增:
    查看 Timer ,它将允许您在定义的 Duration 之后自动递增 hour
    https://fluttermaster.com/tips-to-use-timer-in-dart-and-flutter/
  2. 为您的增量添加条件:
    如果您不想继续调用一个函数来增加您的 hour 变量,您将不得不向 hour 变量添加某种侦听器,看看以下包:

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

    hour 添加侦听器将帮助您定义一个类似于 addHour() 函数的函数,该函数将在 hour 的值更改时自动调用。

    或者您可以在 Timer 本身中添加增量条件。

您可以为此目的使用自定义 setter:

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;
}

那么您可以进行以下操作:

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