Constructors trong Dart
1. Giới thiệu
Constructor là method đặc biệt được gọi khi tạo object mới.
2. Default Constructor
class Person {
String name = '';
int age = 0;
}
void main() {
var person = Person(); // Default constructor
}3. Parameterized Constructor
class Person {
String name;
int age;
// Cách viết đầy đủ
Person(String name, int age) {
this.name = name;
this.age = age;
}
}4. Shorthand Constructor
class Person {
String name;
int age;
// Cách viết ngắn gọn
Person(this.name, this.age);
}
void main() {
var person = Person('Alice', 25);
}5. Named Parameters
class Person {
String name;
int age;
String? city;
Person({
required this.name,
required this.age,
this.city,
});
}
void main() {
var person = Person(name: 'Bob', age: 30, city: 'Hanoi');
}6. Named Constructor
class Point {
double x, y;
Point(this.x, this.y);
Point.origin() : x = 0, y = 0;
Point.fromList(List<double> coords)
: x = coords[0],
y = coords[1];
}
void main() {
var p1 = Point(3, 4);
var p2 = Point.origin();
var p3 = Point.fromList([1, 2]);
}7. Initializer List
class Rectangle {
final double width;
final double height;
final double area;
Rectangle(this.width, this.height)
: area = width * height;
}8. Redirecting Constructor
class Point {
double x, y;
Point(this.x, this.y);
// Redirect đến constructor khác
Point.alongXAxis(double x) : this(x, 0);
Point.alongYAxis(double y) : this(0, y);
}9. Factory Constructor
class Logger {
static final Logger _instance = Logger._internal();
factory Logger() {
return _instance; // Singleton pattern
}
Logger._internal();
void log(String message) => print(message);
}
void main() {
var logger1 = Logger();
var logger2 = Logger();
print(identical(logger1, logger2)); // true
}10. Const Constructor
class Point {
final double x, y;
const Point(this.x, this.y);
}
void main() {
const p1 = Point(1, 2);
const p2 = Point(1, 2);
print(identical(p1, p2)); // true
}📝 Tóm tắt
| Loại | Mục đích |
|---|---|
| Default | Constructor không tham số |
| Parameterized | Nhận tham số |
| Named | Tên tùy chọn như .origin() |
| Factory | Trả về instance (singleton) |
| Const | Tạo compile-time constant |
| Redirecting | Gọi constructor khác |
Last updated on