带有条件的设置变量

问题描述 投票:0回答:1

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

现在我需要增加hour,即dt.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

有办法吗?

flutter dart flutter-layout dart-polymer flutter-animation
1个回答
0
投票
  1. 对于自动递增:查看Timer,它将使您在定义了hour之后自动递增Durationhttps://fluttermaster.com/tips-to-use-timer-in-dart-and-flutter/
  2. 用于为您的增量添加条件:如果不想为了增加hour变量而继续调用函数,则必须在hour变量中添加某种侦听器,请查看以下软件包:property_change_notifier:https://pub.dev/packages/property_change_notifierhour中添加一个侦听器将帮助您定义一个函数,例如addHour()函数,当hour的值更改时,该函数将自动被调用。或者,您可以在Timer本身内添加递增条件。
© www.soinside.com 2019 - 2024. All rights reserved.