Named Constructors
🎯 Mục tiêu: Tạo constructors với tên mô tả.
💡 Cú pháp
Phần tiêu đề “💡 Cú pháp”class Point { double x, y;
Point(this.x, this.y);
// Named constructors Point.origin() : x = 0, y = 0;
Point.fromJson(Map<String, double> json) : x = json['x'] ?? 0, y = json['y'] ?? 0;}
var p1 = Point.origin();var p2 = Point.fromJson({'x': 10, 'y': 20});📱 Trong Flutter - Models
Phần tiêu đề “📱 Trong Flutter - Models”class User { final String id; final String name; final String email;
User({ required this.id, required this.name, required this.email, });
User.fromJson(Map<String, dynamic> json) : id = json['id'], name = json['name'], email = json['email'];
Map<String, dynamic> toJson() => { 'id': id, 'name': name, 'email': email, };}✅ Checklist
Phần tiêu đề “✅ Checklist”- Dùng
ClassName.name()syntax - Initializer list với
: - Common:
fromJson,fromMap