Skip to Content

Class và Object trong Dart

1. Giới thiệu

Class là bản thiết kế để tạo objects. Dart là ngôn ngữ hướng đối tượng thuần túy.

2. Khai báo Class cơ bản

class Person { String name = ''; int age = 0; void introduce() { print('Tôi là $name, $age tuổi'); } } void main() { var person = Person(); person.name = 'Alice'; person.age = 25; person.introduce(); }

3. Constructor

class Person { String name; int age; // Constructor Person(this.name, this.age); void introduce() { print('Tôi là $name, $age tuổi'); } } void main() { var person = Person('Bob', 30); person.introduce(); }

4. Named Constructor

class Point { double x, y; Point(this.x, this.y); // Named constructor Point.origin() : x = 0, y = 0; Point.fromJson(Map<String, double> json) : x = json['x']!, y = json['y']!; } void main() { var p1 = Point(3, 4); var p2 = Point.origin(); var p3 = Point.fromJson({'x': 1.0, 'y': 2.0}); }

5. Private members

class BankAccount { String _accountNumber; // Private double _balance = 0; // Private BankAccount(this._accountNumber); double get balance => _balance; void deposit(double amount) { _balance += amount; } }

6. Getters và Setters

class Rectangle { double width, height; Rectangle(this.width, this.height); // Getter double get area => width * height; // Setter set dimension(double value) { width = value; height = value; } } void main() { var rect = Rectangle(5, 3); print(rect.area); // 15 rect.dimension = 4; // Sets both }

7. Static members

class Math { static const double pi = 3.14159; static int max(int a, int b) => a > b ? a : b; } void main() { print(Math.pi); // 3.14159 print(Math.max(5, 3)); // 5 }

8. Final và Const fields

class Person { final String id; // Phải gán trong constructor final String name; static const String species = 'Human'; Person(this.id, this.name); }

9. Cascade notation (..)

class Person { String name = ''; int age = 0; String city = ''; } void main() { var person = Person() ..name = 'Alice' ..age = 25 ..city = 'Hanoi'; }

📝 Tóm tắt

  • Class định nghĩa blueprint cho objects
  • Constructor khởi tạo object
  • _ prefix tạo private member
  • Getter/Setter kiểm soát truy cập
  • Static member thuộc về class
  • Cascade .. gọi nhiều method liên tiếp
Last updated on