void main() {
Car c1 = new Car('E1001');
}
class Car {
String engine;
Car(String engine) {
this.engine = engine;
print("The engine is : ${engine}");
}
}
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.
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.
In the dart null-safety feature,
either make the engine variable nullable by ?
,
class Car {
String? engine;
Car(String engine){
this.engine = engine;
print("The engine is : ${engine}");
}
}
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}");
}
}
or initialize the variable in the constructor's initialize block.
class Car {
String engine;
Car(String engine) : engine = engine {
print("The engine is : ${engine}");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With