On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The Default Constructor
  4. 2. Named Constructors
  5. 3. The Initializer List
  6. 4. The Constructor Dart Gives You
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 031: Default & Named Constructors

Day11: Classes, Objects & Constructors
Lecture031 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

Creating an object and then setting each field by hand (Lecture 030) is slow, and it's easy to forget one. A constructor sets the fields the moment the object is created. A class can also have named constructors for different ways of creating it.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lecture 030 (classes and objects).


Learning Objectives

  • Write a default (unnamed) constructor
  • Use the this.field shortcut
  • Write named constructors like Student.guest()
  • Set fields in an initializer list (: field = value)
  • Know when Dart provides a constructor for you

1. The Default Constructor

A constructor has the same name as the class and no return type. this.name in the brackets means "put this argument straight into the name field":

dart
class Student {
  String name;
  int grade;

  Student(this.name, this.grade);

  void show() => print('$name, grade $grade');
}

var s1 = Student('Ali', 7);
s1.show();   // Ali, grade 7

Now the fields don't need starting values (String name; is fine), because the constructor always sets them.

2. Named Constructors

A class can have only one unnamed constructor, but as many named ones as you like: ClassName.something(...).

dart
class Student {
  String name;
  int grade;

  Student(this.name, this.grade);

  Student.newcomer(this.name) : grade = 1;

  Student.guest()
      : name = 'Guest',
        grade = 0;

  void show() => print('$name, grade $grade');
}

void main() {
  Student('Ali', 7).show();
  Student.newcomer('Sara').show();
  Student.guest().show();
}

Output

code
Ali, grade 7
Sara, grade 1
Guest, grade 0

3. The Initializer List

The part after : is the initializer list. It sets fields before the object is ready, separated by commas. It's where you set fields that aren't passed in directly, or that need calculating:

dart
class Temperature {
  double celsius;
  Temperature(this.celsius);
  Temperature.fromFahrenheit(double f) : celsius = (f - 32) * 5 / 9;
}

var t = Temperature.fromFahrenheit(98.6);
print(t.celsius.toStringAsFixed(1));   // 37.0

Names like fromFahrenheit, fromJson or empty tell the reader how the object is being made.

4. The Constructor Dart Gives You

If you write no constructor at all, Dart provides an empty default one, which is why Car() worked in Lecture 030:

dart
class Point {
  int x = 0;
  int y = 0;
}

var p = Point();
print('${p.x}, ${p.y}');   // 0, 0

As soon as you write any constructor yourself, that free one disappears.


Code Examples

Example 1: Products in a Shop

dart
class Product {
  String name;
  double price;
  int stock;

  Product(this.name, this.price, this.stock);

  Product.outOfStock(this.name, this.price) : stock = 0;

  Product.freebie(this.name)
      : price = 0,
        stock = 100;

  void show() {
    var status = stock == 0 ? 'out of stock' : '$stock in stock';
    print('$name: Rs $price ($status)');
  }
}

void main() {
  Product('Headphones', 2500, 12).show();
  Product.outOfStock('Smart Watch', 8900).show();
  Product.freebie('Sticker').show();
}

Output

code
Headphones: Rs 2500.0 (12 in stock)
Smart Watch: Rs 8900.0 (out of stock)
Sticker: Rs 0.0 (100 in stock)

Three ways to create a product, each with a name that says what it means.


Common Beginner Mistakes

1. Two unnamed constructors

dart
class Student {
  String name;
  Student(this.name);
  Student(String n, int age) : name = n;
}
code
Error: 'Student' is already declared in this scope.

Give the second one a name: Student.withAge(...).

2. Calling the constructor without its arguments

dart
var s = Student();
code
Error: Too few positional arguments: 1 required, 0 given.

Once you write Student(this.name), the free empty constructor is gone. Pass the name, or add a named constructor such as Student.guest().

3. A named constructor that forgets a field

dart
class Student {
  String name;
  Student.guest();
}
code
Error: Field 'name' should be initialized because its type 'String' doesn't allow null.

Every constructor must set every non-nullable field: Student.guest() : name = 'Guest';.


Practice Questions

  1. What is the name of a class's default constructor?
  2. What does this.price mean inside a constructor's brackets?
  3. Write a named constructor Product.sample() that sets name = 'Sample', price = 0, stock = 1.
  4. Why does var p = Point(); work when Point has no constructor?
  5. How many unnamed constructors can a class have?

Practice Answers

  1. The same as the class: Student(...).
  2. Take this argument and store it in the price field.
dart
Product.sample()
    : name = 'Sample',
      price = 0,
      stock = 1;
  1. Dart adds an empty default constructor when you don't write any.
  2. One. Use named constructors for the others.

Key Takeaways

  • A constructor runs when an object is created and sets its fields.
  • ClassName(this.a, this.b) copies arguments straight into fields.
  • Named constructors (ClassName.name(...)) give extra, self-explaining ways to create objects.
  • The initializer list (: field = value) sets fields that need a fixed or calculated value.
  • Every constructor must set every non-nullable field.