What is a Constructor?
A constructor is a special method that runs when you create an object. It initializes the object's fields. In Dart, a constructor has the same name as the class.
Default Constructor
class Point {
double x;
double y;
// Constructor
Point(double x, double y) {
this.x = x;
this.y = y;
}
}
var p = Point(3.0, 4.0);
print('$${p.x}, $${p.y}'); // 3.0, 4.0
Initializing Formal Parameters
Dart provides a shorthand to initialize fields directly in the constructor signature using this.fieldName:
class Point {
double x;
double y;
// Shorthand — automatically assigns x and y
Point(this.x, this.y);
}
// Equivalent to the verbose version above
Initializer List
Run code before the constructor body using an initializer list (after :). Useful for computing final field values or validation:
class Circle {
final double radius;
final double area;
Circle(double r)
: radius = r,
area = 3.14159 * r * r {
print('Circle created with radius $radius');
}
}
var c = Circle(5.0);
print('Area: $${c.area.toStringAsFixed(2)}');
Output:Circle created with radius 5.0
Area: 78.54
Example
class Employee {
final String id;
final String name;
final String department;
double salary;
Employee({
required this.id,
required this.name,
required this.department,
this.salary = 50000.0,
});
void applyRaise(double percent) {
salary *= (1 + percent / 100);
print('$name raised to \$$${salary.toStringAsFixed(2)}');
}
}
void main() {
var emp1 = Employee(id: 'E001', name: 'Alice', department: 'Engineering');
var emp2 = Employee(id: 'E002', name: 'Bob', department: 'Sales', salary: 45000);
emp1.applyRaise(10); // Alice raised to $55000.00
emp2.applyRaise(5); // Bob raised to $47250.00
}
🧠 Quiz
1. What does Point(this.x, this.y) do?
- A) Calls a method
- B) Automatically assigns constructor parameters to fields ✅
- C) Creates a copy
- D) Initializes x and y to 0
Summary
Constructors initialize object fields when an instance is created. Use the this.field shorthand for concise initialization. Initializer lists (:) run before the constructor body, useful for final fields and computed values. Named parameters with required make constructors explicit and safe.