dart Classes Constructors


Example

A 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:

class Person {
  String name;
  String gender;
  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);