Skip to Content
Dart📘 Ngôn ngữ DartNamed Constructors

Named Constructors trong Dart

🎯 Mục tiêu: Tạo constructors với tên mô tả.


💡 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

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

  • Dùng ClassName.name() syntax
  • Initializer list với :
  • Common: fromJson, fromMap

Last updated on