1
class Car {
  String model;
  String brand;
  String _engine;
  static int carProduced = 0;
  Car(String model, String brand, String engine) {
    this._engine = engine;
    this.brand = brand;
    this.model = model;
  }
}

I am getting this error.

Non-nullable instance field '_engine' must be initialized.
Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.

I am not actually sure. As I am initializing that non-nullable field in the default constructor why do I need to use a late modifier here?

String model = "";
  String brand = "";
  String _engine = "";

Adding initializer expression solved the error. Does it mean that object fields are created even before the constructor call ??

  • See [How do I initialize non-nullable members in a constructor body?](https://stackoverflow.com/q/66725613/) and https://stackoverflow.com/a/63319094/ – jamesdlin Jan 23 '22 at 20:05

1 Answers1

0

Dart objects are created in two steps/phases:

  1. Initialization of values.
  2. Execution of constructor body.

So all non-nullable non-late values must have a value before we executes the constructor body. The reason is that inside the constructor body we are allowed to use all values inside the object.

We can therefore in Dart run initialization code before running the constructor body like:

class Car {
  String model;
  String brand;
  String _engine;
  static int carProduced = 0;

  Car(String model, String brand, String engine)
      : this.model = model,
        this.brand = brand,
        this._engine = engine;
}

But since this is kinda redundant we have the follow shortcut to do the same:

class Car {
  String model;
  String brand;
  String _engine;
  static int carProduced = 0;
  
  Car(this.model, this.brand, this._engine);
}
julemand101
  • 28,470
  • 5
  • 52
  • 48