I am trying to add default initializer:
class Foo {
DateTime? date;
Foo({this.date}) {
date ??= DateTime.now();
}
}
class Foo2 {
DateTime date;
Foo2({this.date}) : date ??= DateTime.now(); // <= error
}
void main() {}
The only way I fould is to make the member nullable and initialize if within the constructor body.
Is there any better way (to make member non-nullable)?
Would the following be an acceptable solution? It does require the parameter ,to the constructor, to be nullable and a value of
nullhaving the implicit meaning of a default value is then used:(And yes, the syntax are correct. Dart are smart enough here to know that we cannot assign a new value to the parameter
dateas part of the initialization phase of constructing the object. So thedateindate =would automatically mean the class variabledateand not the constructor argumentdate. And since we cannot get any values from the object in this phase either, the second use ofdateis using the class parameter.)