On this page11 sections
Lecture 031: Default & Named Constructors
| Day | 11: Classes, Objects & Constructors |
| Lecture | 031 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
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.fieldshortcut - 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":
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 7Now 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(...).
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
Ali, grade 7
Sara, grade 1
Guest, grade 03. 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:
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.0Names 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:
class Point {
int x = 0;
int y = 0;
}
var p = Point();
print('${p.x}, ${p.y}'); // 0, 0As soon as you write any constructor yourself, that free one disappears.
Code Examples
Example 1: Products in a Shop
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
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
class Student {
String name;
Student(this.name);
Student(String n, int age) : name = n;
}Error: 'Student' is already declared in this scope.Give the second one a name: Student.withAge(...).
2. Calling the constructor without its arguments
var s = Student();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
class Student {
String name;
Student.guest();
}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
- What is the name of a class's default constructor?
- What does
this.pricemean inside a constructor's brackets? - Write a named constructor
Product.sample()that setsname = 'Sample',price = 0,stock = 1. - Why does
var p = Point();work whenPointhas no constructor? - How many unnamed constructors can a class have?
Practice Answers
- The same as the class:
Student(...). - Take this argument and store it in the
pricefield.
Product.sample()
: name = 'Sample',
price = 0,
stock = 1;- Dart adds an empty default constructor when you don't write any.
- 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.