Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}");
  }
}
like image 916
Kodala Parth Avatar asked Apr 12 '21 10:04

Kodala Parth


People also ask

How do I add a field initializer to a constructor?

Add a field initializer in this constructor You initialize the field in the Initializer list, which is placed before a constructor body. It has the following syntax: You put a colon ( : ) before a constructor body. You assign each instance variable after the colon.

What is an initializer expression?

An initialization expression initializes a new object. Most initialization expressions are supported, including most new C# 3.0 and Visual Basic 9.0 initialization expressions.


Video Answer


1 Answers

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}");
      }
    }
    
like image 155
Ravi Sevta Avatar answered Oct 16 '22 15:10

Ravi Sevta