Dart Constructors
Dart Constructors
A constructor is a special function that creates an object from a class.
It has the same name as the class, and it has no return type.
The most common kind is called a generative constructor, because it generates a new object every time it is called.
Here is a constructor with a body, which sets the fields and prints a message:
Example
class Car {
String brand = '';
int year = 0;
Car(String brand, int year) {
this.brand = brand;
this.year = year;
print('A new $brand was created');
}
}
void main() {
var myCar = Car('Volvo', 2020);
print(myCar.year);
}
Try it Yourself »
Result:
A new Volvo was created
2020
This works, but the fields need a starting value ('' and 0), because they must have a value before the body of the constructor runs.
The this.x Shorthand
Setting fields from parameters is so common that Dart has a short form for it.
When you write this.brand as a parameter, the argument goes directly into the field brand:
Example
class Car {
String brand;
int year;
Car(this.brand, this.year);
}
void main() {
var myCar = Car('Volvo', 2020);
print('${myCar.brand} ${myCar.year}');
}
Try it Yourself »
Result:
Volvo 2020
The constructor has no body, so it ends with a semicolon.
The fields do not need a starting value, because they get their value before the object is ready.
This also works with final fields, which cannot be changed after the object is created:
Example
class Person {
final String name;
final int age;
Person(this.name, this.age);
}
void main() {
var person = Person('Emma', 30);
print('${person.name} is ${person.age} years old');
}
Try it Yourself »
Result:
Emma is 30 years old
Tip: Make fields final when they should not change.
It makes your classes safer and easier to understand.
Initializer List
Sometimes a field gets a value that is calculated from the parameters.
For this, you can use an initializer list.
It comes after a colon :, before the body of the constructor, and the parts are separated by commas:
Example
class Rectangle {
final double width;
final double height;
final double area;
Rectangle(this.width, this.height) : area = width * height;
}
void main() {
var room = Rectangle(4, 5);
print('Area: ${room.area}');
}
Try it Yourself »
Result:
Area: 20.0
The initializer list runs before the body, so it can set final fields.
The initializer list can set more than one field, and it can use parameters that are not fields:
Example
class User {
final String name;
final String email;
User(String name, String email)
: name = name.trim(),
email = email.toLowerCase();
}
void main() {
var user = User(' Olivia ', 'Olivia@Example.com');
print('[${user.name}]');
print(user.email);
}
Try it Yourself »
Result:
[Olivia]
olivia@example.com
In name = name.trim(), the left name is the field, and the right name is the parameter.
Named Parameters in Constructors
Constructors can have named parameters, just like functions.
Use required for the values that must always be given, and a default value for the others:
Example
class Pizza {
final String name;
final String size;
final bool extraCheese;
Pizza({required this.name, this.size = 'medium', this.extraCheese = false});
}
void main() {
var p1 = Pizza(name: 'Margherita');
var p2 = Pizza(name: 'Pepperoni', size: 'large', extraCheese: true);
print('${p1.name}, ${p1.size}, ${p1.extraCheese}');
print('${p2.name}, ${p2.size}, ${p2.extraCheese}');
}
Try it Yourself »
Result:
Margherita, medium, false
Pepperoni, large, true
Named arguments make it easy to see what each value means, and you can write them in any order.
If you forget a required argument, the program does not run:
Example
class Pizza {
final String name;
final String size;
Pizza({required this.name, this.size = 'medium'});
}
void main() {
var pizza = Pizza(size: 'small');
print(pizza.name);
}
Try it Yourself »
Result:
main.dart:9:20: Error: Required named parameter 'name' must be provided.
var pizza = Pizza(size: 'small');
^
main.dart:5:3: Context: Found this candidate, but the arguments don't match.
Pizza({required this.name, this.size = 'medium'});
^^^^^
Const Constructors
If all the fields of a class are final, you can mark the constructor with const.
Then you can create objects that are compile-time constants, which means their values are known before the program runs.
Dart creates each constant object only once, and reuses it when you create the same constant again:
Example
class Point {
final int x;
final int y;
const Point(this.x, this.y);
}
void main() {
const a = Point(1, 2);
const b = Point(1, 2);
var c = Point(1, 2);
print(identical(a, b));
print(identical(a, c));
}
Try it Yourself »
Result:
true
false
The function identical() returns true when two variables point to the very same object.
a and b are the same object, but c is a new object, because it was not created with const.