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

7,252

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}");
      }
    }
    
Share:
7,252
Kodala Parth
Author by

Kodala Parth

Updated on December 29, 2022

Comments

  • Kodala Parth
    Kodala Parth over 1 year
    void main() {
      Car c1 = new Car('E1001');
    }
    
    class Car {
      String engine;
      Car(String engine) {
        this.engine = engine;
        print("The engine is : ${engine}");
      }
    }
    
  • vietstone
    vietstone over 2 years
    or on more constructor: Car(this.engine);