【问题标题】:Flutter define default value of a DateTime in constructorFlutter 在构造函数中定义 DateTime 的默认值
【发布时间】:2021-04-16 13:55:34
【问题描述】:

我有以下状态,想在构造函数中设置 DateTime 的默认值。我想将当前日期作为默认日期,但我不确定这是否可能,因为它需要保持不变。
DateTime.now() 函数或例如 DateTime.utc(1989, 11, 9) 也不起作用,但还有其他方法可以分配默认日期时间吗?

class CreateDidState {
  final String firstname;
  final String lastName;
  final String email;
  final String phoneNumber;
  final DateTime dateOfBirth;
  final String sex;
  final String address;
  final String city;
  final String state;
  final String postalCode;
  final String country;

  CreateDidState(
      {this.firstname = "",
      this.lastName = "",
      this.email = "",
      this.phoneNumber = "",
      this.dateOfBirth = DateTime.now(), //The default value of an optional parameter must be constant.
      this.sex = "",
      this.address = "",
      this.city = "",
      this.state = "",
      this.postalCode = "",
      this.country = ""});
}

【问题讨论】:

    标签: flutter datetime dart


    【解决方案1】:

    问题在于DateTime.now() 不是常量,这是有道理的,因为常量意味着可以在编译程序时确定该值,因此如果此构造函数是,我们将在编译程序时获得DateTime 值标记为const

    正如您得到的错误所表明的那样,您必须使用一个常量评估值作为默认值。但是我们可以在这里做一个小技巧:

    class CreateDidState {
      final String firstname;
      final String lastName;
      final String email;
      final String phoneNumber;
      final DateTime dateOfBirth;
      final String sex;
      final String address;
      final String city;
      final String state;
      final String postalCode;
      final String country;
    
      CreateDidState(
          {this.firstname = "",
          this.lastName = "",
          this.email = "",
          this.phoneNumber = "",
          DateTime? dateOfBirth,
          this.sex = "",
          this.address = "",
          this.city = "",
          this.state = "",
          this.postalCode = "",
          this.country = ""})
          : this.dateOfBirth = dateOfBirth ?? DateTime.now();
    }
    

    我们在这里所做的是将参数dateOfBirth 声明为可空值(DateTime?)。由于命名参数的默认值为null,这意味着我们不需要指定任何默认值。

    但我们仍然希望类字段dateOfBirth 是一个不可为空的值。所以我从参数中删除了this.,所以这个构造函数参数与类变量无关。

    然后,我将以下代码添加到构造函数的类初始化程序部分(此代码作为创建对象的一部分运行,并且允许使用值初始化类变量):

          : this.dateOfBirth = dateOfBirth ?? DateTime.now();
    

    这意味着我们希望类变量dateOfBirth(我们使用this. 告诉两个变量,同名,分开)具有表达式dateOfBirth ?? DateTime.now() 的值。

    ?? 表示我们返回左边的值,除非该值为null。如果null,我们将值返回到右边。所以如果dateOfBirthnull(如果我们不给参数一个值,因为null 是默认值)我们使用DateTime.now() 创建的值。

    【讨论】:

    • 你能解释一下你的答案吗?我真的不明白你的格式
    • @genericUser 抱歉,答案很弱。由于我可以看到问题(和我的答案)变得有点受欢迎,我认为它已经赢得了获得适当解释的权利。如果我在回答中遗漏了任何重要的细节,请告诉我。 :)
    • 谢谢@julemand101!很好的解释!
    猜你喜欢
    • 2020-12-31
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多