Reputation: 1566
Let's assume a simple class like this
class MyClass {
String aString;
DateTime aDate;
MyClass({this.aString = '', this.aDate = DateTime.now()});
}
This code does not work because optional parameters must be constant. I do not want aDate
be nullable.
I can do this:
class MyClass {
String aString;
DateTime aDate;
MyClass({this.aString = ''}) : this.aDate = DateTime.now();
}
This is accepted by the compiler but I cannot set aDate
when constructing an instance of MyClass
like so:
var c = MyClass(aString: 'bla bla', aDate: DateTime(2021, 9, 20));
Instead it seams I have to write:
var c = MyClass(aString: 'bla bla');
c.aDate = DateTime(2021, 9, 20);
Is there really no better way to initialize complex objects with optional named parameters in constructors with null safety turned on? This is just a simplified sample. In reality, I have classes with lots of complex objects that I get from a remote server. The method shown above forces me to write hundreds of lines of assignment statements.
Upvotes: 1
Views: 85
Reputation: 17141
You can use the following:
class MyClass {
String aString;
DateTime aDate;
MyClass({this.aString = '', DateTime? aDate}) : aDate = aDate ?? DateTime.now();
}
You were on the right track, you just needed to combine the two methods you provided above. This uses an optional named parameter, which must be nullable, and only assigns it to this.aDate
when it's not null
using the ??
operator. If it is null
, it uses your desired default value of DateTime.now()
.
Upvotes: 1