Constructor types
- Dart course
- Intermediate
- Lesson 1/116
- 5 min
Learn named and default constructors.
What is a constructor?
A constructor is a special method called when a new instance is created. In Dart the constructor shares the class name; no return type is written.
Example: class User { String name; User(this.name); }. Here User(this.name) is the default constructor; the this.name shortcut assigns the parameter directly to the field. The constructor is called by the class name without new: User('Alex'). A Dart class can have at most one default constructor; for more, use a named constructor.
Default and named
Dart has two main constructor kinds. A default constructor shares the class name and assigns parameters directly to fields: User(this.name). Only one is allowed per class.
When a second constructor is needed, use a named constructor: User.guest() : name = 'Guest';. The .guest suffix gives the constructor a name. A class can hold one default and many named constructors side by side; this is Dart's replacement for overloading.
Practice Define the User class
Define a class named User. Add a String name field. Write a default constructor of the form User(this.name). In main, create a User('Alex') instance and print its name field with print.
Starter code
// Define the User class
// Add a String name field
// Write the default constructor using the this.name shortcut
void main() {
// Create a User('Alex') instance and print its name
}Sample solution
// Define the User class
class User {
String name;
User(this.name);
}
void main() {
var u = User('Alex');
print(u.name);
}Expected output
Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid Dart constructor declaration?
- User(this.name); Correct answer
- function User(this.name);
- constructor User(this.name);
- new User(this.name);
Explanation: A constructor is declared as a method with the same name as the class; no extra keyword is needed.
2 Complete the constructor body
class User {
String name;
User(____);
}
class User {
String name;
User(this.name);
}
Explanation: The this.name shortcut assigns the parameter to the field with the same name.
3 Match the constructor parts
| Term | Meaning |
|---|---|
User |
Class and constructor name |
this.name |
Field assignment shortcut |
User('Ayşe') |
Instance creation call |