Class và Object trong Dart
🎯 Mục tiêu: OOP cơ bản với class trong Dart.
💡 Định nghĩa Class
class Person {
String name;
int age;
Person(this.name, this.age);
void greet() {
print("Hello, I'm $name");
}
}
void main() {
var person = Person("Alice", 25);
person.greet();
}📝 Properties
class User {
final String id;
String name;
int _age = 0; // Private (underscore)
User(this.id, this.name);
int get age => _age;
set age(int value) {
if (value >= 0) _age = value;
}
}🔧 Initializer List
class Point {
final double x;
final double y;
final double distance;
Point(double x, double y)
: x = x,
y = y,
distance = sqrt(x * x + y * y);
}📱 Trong Flutter
class UserModel {
final String id;
final String name;
final String? avatar;
const UserModel({
required this.id,
required this.name,
this.avatar,
});
}✅ Checklist
- Dùng
this.trong constructor -
_prefix cho private - Getters và setters
Last updated on