Constructor in Dart

Find this useful? Support us: Star on GitHub 6
Category: Class | Language: Dart

In Dart, a constructor is a special method used to create and initialize objects within a class. Constructors have the same name as the class and can be used to set default values for object properties or perform other operations when the object is created.

There are two types of constructors in Dart:

1. Default Constructor: It is automatically generated by Dart when there is no constructor available in the class. It does not take any arguments and initializes the object with default values.

Example:

class Student {
  String name;
  int age;

Student() {
name = 'No Name';
age = 0;
}
}

void main() {
Student s = new Student();
print('Name: ${s.name}');
print('Age: ${s.age}');
}

In the above example, we created a Student class with a default constructor that initializes the object with default values. We then created an object of the Student class and printed its properties.

Output:

Name: No Name
Age: 0

2. Parameterized Constructor: It is a constructor that takes one or more arguments to initialize object properties.

Example:

class Student {
  String name;
  int age;

Student(String n, int a) {
name = n;
age = a;
}
}

void main() {
Student s = new Student('John', 21);
print('Name: ${s.name}');
print('Age: ${s.age}');
}

In the above example, we created a Student class with a parameterized constructor that takes two arguments n and a to initialize object properties. We then created an object of the Student class with the values 'John' and 21 and printed its properties.

Output:

Name: John
Age: 21

Alternatively, constructors can also be defined using the shorthand syntax that uses this keyword to initialize object properties.

Example:

class Student {
  String name;
  int age;

Student(this.name, this.age);
}

void main() {
Student s = new Student('John', 21);
print('Name: ${s.name}');
print('Age: ${s.age}');
}

In the above example, we created a Student class with a parameterized constructor using shorthand syntax that initializes the name and age properties using this keyword. We then created an object of the Student class with the values 'John' and 21 and printed its properties.

Output:

Name: John
Age: 21