Constructors trong Dart
🎯 Mục tiêu: Các loại constructors trong Dart.
💡 Default Constructor
class Person {
String name;
int age;
// Short syntax
Person(this.name, this.age);
// Full syntax
// Person(String name, int age) {
// this.name = name;
// this.age = age;
// }
}📝 Named Constructor
class Point {
double x, y;
Point(this.x, this.y);
Point.origin() : x = 0, y = 0;
Point.fromJson(Map<String, double> json)
: x = json['x']!,
y = json['y']!;
}
var p1 = Point(10, 20);
var p2 = Point.origin();
var p3 = Point.fromJson({'x': 5, 'y': 10});🔧 Const Constructor
class ImmutablePoint {
final double x, y;
const ImmutablePoint(this.x, this.y);
}
// Compile-time constant
const origin = ImmutablePoint(0, 0);🎯 Factory Constructor
class Logger {
static final Map<String, Logger> _cache = {};
final String name;
factory Logger(String name) {
return _cache.putIfAbsent(name, () => Logger._internal(name));
}
Logger._internal(this.name);
}✅ Checklist
-
this.shorthand - Named constructors
-
constconstructors -
factorycho singletons/caching
Last updated on