How to initialize class non-nullable member with a default non-constant initializer in Dart?

40 Views Asked by At

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)?

2

There are 2 best solutions below

0
julemand101 On BEST ANSWER

Would the following be an acceptable solution? It does require the parameter ,to the constructor, to be nullable and a value of null having the implicit meaning of a default value is then used:

class Foo {
  DateTime date;

  Foo({DateTime? date}) : date = date ?? DateTime.now();
}

(And yes, the syntax are correct. Dart are smart enough here to know that we cannot assign a new value to the parameter date as part of the initialization phase of constructing the object. So the date in date = would automatically mean the class variable date and not the constructor argument date. And since we cannot get any values from the object in this phase either, the second use of date is using the class parameter.)

0
WebDesk Solution On

This way, If you don't provide a date when creating the object, it will automatically use the current date and time.

class Foo2 {
  DateTime date;
  Foo2({DateTime? date}) : date = date ?? DateTime.now();
}

I hope this helps!