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

Named Constructors trong Dart

1. Giới thiệu

Named constructor cho phép định nghĩa nhiều cách khởi tạo khác nhau cho một class.

2. Cú pháp

class ClassName { ClassName.constructorName() { // initialization } }

3. Ví dụ cơ bản

class Point { double x, y; // Default constructor Point(this.x, this.y); // Named constructors Point.origin() : x = 0, y = 0; Point.onXAxis(double x) : this.x = x, y = 0; Point.onYAxis(double y) : x = 0, this.y = y; } void main() { var p1 = Point(3, 4); var p2 = Point.origin(); var p3 = Point.onXAxis(5); var p4 = Point.onYAxis(10); }

4. fromJson Constructor

class User { String name; int age; String email; User(this.name, this.age, this.email); User.fromJson(Map<String, dynamic> json) : name = json['name'], age = json['age'], email = json['email']; } void main() { var json = {'name': 'Alice', 'age': 25, 'email': 'alice@email.com'}; var user = User.fromJson(json); }

5. toJson Method

class User { String name; int age; User(this.name, this.age); User.fromJson(Map<String, dynamic> json) : name = json['name'], age = json['age']; Map<String, dynamic> toJson() { return {'name': name, 'age': age}; } }

6. Copy Constructor

class Person { String name; int age; Person(this.name, this.age); // Copy constructor Person.copy(Person other) : name = other.name, age = other.age; // copyWith pattern Person copyWith({String? name, int? age}) { return Person( name ?? this.name, age ?? this.age, ); } } void main() { var original = Person('Alice', 25); var copy = Person.copy(original); var modified = original.copyWith(age: 26); }

7. Ví dụ thực tế với DateTime

class Event { String title; DateTime date; Event(this.title, this.date); Event.now(this.title) : date = DateTime.now(); Event.tomorrow(this.title) : date = DateTime.now().add(Duration(days: 1)); Event.scheduled(this.title, int year, int month, int day) : date = DateTime(year, month, day); }

8. Với Optional Parameters

class Config { String host; int port; bool secure; Config({ required this.host, this.port = 80, this.secure = false, }); Config.development() : host = 'localhost', port = 3000, secure = false; Config.production() : host = 'api.example.com', port = 443, secure = true; }

📝 Tóm tắt

  • Named constructor có tên rõ ràng .constructorName()
  • Phổ biến: .fromJson(), .copy(), .empty()
  • Giúp code dễ đọc và ý nghĩa rõ ràng
  • Có thể có nhiều named constructor trong 1 class
  • Kết hợp với initializer list
Last updated on