'Error: Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'

void main() {
  Car c1 = new Car('E1001');
}

class Car {
  String engine;
  Car(String engine) {
    this.engine = engine;
    print("The engine is : ${engine}");
  }
}


Solution 1:[1]

In the dart null-safety feature,

  1. either make the engine variable nullable by ?,

    class Car {
      String? engine;
      Car(String engine){
         this.engine = engine;
         print("The engine is : ${engine}");
      }
    }
    
  2. or add the late keyword to initialise it lazily,

    class Car {
      late String engine;
      Car(String engine){
         this.engine = engine;
         print("The engine is : ${engine}");
      }
    }
    
  3. or initialize the variable in the constructor's initialize block.

    class Car {
      String engine;
      Car(String engine) : engine = engine {
         print("The engine is : ${engine}");
      }
    }
    

Solution 2:[2]

Update, for initialize the variable in the constructor's:

class Car{
    String name;
    int wights; 
    Car(this.name,this.wigths);
    Car.origin(): this.name='', this.wigths=0;
  }

Solution 3:[3]

Using late keyword you can make a null variable.

Ex: late String engine;

"?" used for making null value.

Ex: String? engine;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Gabriel Vásquez
Solution 3 Kodala Parth