【问题标题】:Initialising multiple DateTime variables in a Flutter class在 Flutter 类中初始化多个 DateTime 变量
【发布时间】:2021-10-20 01:35:02
【问题描述】:

我有一个 Reminder 类,它有两个日期变量 - startDate 和 endDate。

class Reminder {
  
  final String name;
  final String type;
  final DateTime startDate;
  final String repeatFrequency;
  final DateTime endDate;
  
  Reminder({this.name = "", this.type = "", DateTime startDate = DateTime.utc(2021,1,1),
            this.repeatFrequency = "", DateTime endDate = DateTime.utc(2021,1,1)})
  
}

当我初始化类时,我收到一条错误消息“可选参数的默认值必须是常量”。基于this article,我尝试了以下方法:

  Reminder({this.name = "", this.type = "", DateTime? startDate,
            this.repeatFrequency = "", DateTime? endDate}) : 
  this.startDate = (startDate != null ? startDate : DateTime.utc(2021,1,1))

这种方法现在似乎有效,但是我只能对 startDate 而不是 endDate 这样做。有没有办法用这种方法初始化两个变量?

【问题讨论】:

    标签: flutter datetime


    【解决方案1】:

    你可以试试下面这段代码:

      Reminder({this.name = "", this.type = "", DateTime? startDate,
        this.repeatFrequency = "", DateTime? endDate}) :
            this.startDate = (startDate != null ? startDate : DateTime.utc(2021,1,1)), 
            this.endDate = endDate ?? DateTime.utc(2021,1,1);
    

    【讨论】:

      猜你喜欢
      • 2011-04-02
      • 1970-01-01
      • 2013-03-04
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多