Constructors
🎯 Mục tiêu: Các loại constructors trong Dart.
💡 Default Constructor
Phần tiêu đề “💡 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
Phần tiêu đề “📝 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
Phần tiêu đề “🔧 Const Constructor”class ImmutablePoint { final double x, y;
const ImmutablePoint(this.x, this.y);}
// Compile-time constantconst origin = ImmutablePoint(0, 0);🎯 Factory Constructor
Phần tiêu đề “🎯 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
Phần tiêu đề “✅ Checklist”-
this.shorthand - Named constructors
-
constconstructors -
factorycho singletons/caching