Constructors
suggest changeA class constructor must have the same name as its class.
Let’s create a constructor for a class Person:
class Person {
String name;
String gender;
int age;
Person(this.name, this.gender, this.age);
}
The example above is a simpler, better way of defining the constructor than the following way, which is also possible. Under null safety, a non-nullable field assigned in the constructor body must be late or nullable:
class Person {
late String name;
late String gender;
late int age;
Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
}
Now you can create an instance of Person like this:
var alice = new Person('Alice', 'female', 21);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents