flutter - 用 Dart 条件设置变量

标签 flutter dart flutter-layout dart-polymer flutter-animation

我有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)

有办法吗?

最佳答案

您可以为此使用自定义 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 
}

关于flutter - 用 Dart 条件设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60060305/

相关文章:

android - 加载 flutter 时去除图像中的白色闪烁

flutter - 如何使用 Getx 构建动画启动画面?

ios - flutter_blue^0.6.3 文件未找到 #import "google/protobuf/Any.pbobjc.h"Flutter

dart - 从方法fetchData中删除异步修改器

flutter - 带有ListView的Streambuilder在每个图 block 中显示相同的数据?

ios - 如何让iOS应用程序与蓝牙连接?

android - 如何在向下滚动后到达 “SliverPersistentHeader” 的第一项之前将 “SliverList” 固定在顶部?

Flutter list.builder 不滚动

Flutter/Dart - 在我的构建中使用 FutureBuilder 和 Normal 非异步元素?

java - 在 Flutter 中向特定于平台的代码添加依赖项