Dart: Classes & Constructors
What you will learn
Dart's concise class syntax with constructor parameter shorthand, named constructors, and factory constructors.
Defining a class
class Person {
String name;
int age;
// Constructor with shorthand parameter assignment
Person(this.name, this.age);
void sayHello() {
print("Hi, I'm $name");
}
}
var alice = Person('Alice', 25);
alice.sayHello();
this.name in the constructor parameter list automatically assigns the parameter to the field — no boilerplate.
Named constructors
Classes can have multiple constructors with different names:
class User {
final String name;
final String role;
User(this.name, this.role);
User.admin(String name) : this(name, 'admin');
User.guest() : name = 'Guest', role = 'guest';
}
var admin = User.admin('Alice');
var guest = User.guest();
Getters and setters
class Rectangle {
double width, height;
Rectangle(this.width, this.height);
double get area => width * height; // computed property
set scale(double factor) { // setter
width *= factor;
height *= factor;
}
}
var r = Rectangle(10, 5);
print(r.area); // 50
r.scale = 2;
print(r.area); // 200
Static members
class MathUtils {
static double pi = 3.14159;
static int add(int a, int b) => a + b;
}
print(MathUtils.pi); // 3.14159
print(MathUtils.add(2, 3)); // 5
Common mistakes
- Forgetting that Dart fields must be initialized (in constructor initializer, declaration, or constructor body)
- Using
newkeyword — it's optional in Dart 2+, prefer omitting it - Thinking
finalfields can be set after the constructor runs — they must be set in the constructor initializer list - Forgetting to use
this.propertywhen constructor parameter shadows field name (the shorthandthis.xhandles this)
Quick check below!