Home > Back-end >  Initialising multiple DateTime variables in a Flutter class
Initialising multiple DateTime variables in a Flutter class

Time:10-20

I have a Reminder class, which has two date variables - startDate and 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)})
  
}

When I initialise the class I get an error saying "The default value of an optional parameter must be constant." Based on this article I tried the below:

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

This approach seems to now be working, however I can only do it for startDate and not endDate. Is there a way to initialise both variables with this method?

CodePudding user response:

You can try with this code bellow:

  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);
  • Related