CodeBlanks Logo Icon CodeBlanks

Constructor

Learn to define the class constructor.

Constructor

The constructor is a special method called when an instance is created. It shares the class name. Example: class User { String name; User(this.name); }.

Here User(this.name) is the short form; it means 'assign the parameter to the same-named field'. The long form: User(String name) { this.name = name; }.

The constructor prepares the object: it sets field values, allocates resources. Calling User('Ayşe') returns a User instance with name set to 'Ayşe'. This lesson focuses on the this.name shorthand; the this keyword is covered in a separate lesson.

Short and long form

The short form is very common in Dart constructors: User(this.name). It means 'assign the parameter to the same-named field'. The field name is filled automatically.

The long form is more explicit: User(String name) { this.name = name; }. Here you assign the parameter name to the field with this.name. this means 'this instance'.

Both do the same thing. The short form is the idiomatic Dart style; it is preferred in practice. The long form helps when you need extra logic.

Practice User constructor

Define a User class with a String name field and a User(this.name) constructor. Inside main create an instance with User('Ayşe') and print it with print(u.name).

Starter code

main.dart
void main() {
  // define the User class and constructor

  // create an instance and print
}

Sample solution

main.dart
class User {
  String name;
  User(this.name);
}

void main() {
  var u = User('Ayşe');
  print(u.name);
}

Expected output

Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the constructor parts

Term Meaning
User Constructor name
this.name Shorthand assign
User('Ayşe') Instance creation
name Property name

2 What does User(this.name) do?

  • Throws an error
  • Ignores the name parameter
  • Deletes the class
  • Assigns the name parameter to the name field Correct answer

Explanation: this.name is the shorthand assignment.

3 Constructor short form

Question
class User {
  String name;
  User(____);
}
Answer
class User {
  String name;
  User(this.name);
}

Explanation: this.name assigns the parameter to the field.

All lessons in Beginner