Enumerations (Enums) trong Dart
1. Giới thiệu
Enum định nghĩa một tập hợp các hằng số có tên, giúp code rõ ràng và an toàn hơn.
2. Khai báo Enum cơ bản
enum Color { red, green, blue }
enum DayOfWeek {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday
}
void main() {
var today = DayOfWeek.friday;
print(today); // DayOfWeek.friday
}3. Truy cập các giá trị
void main() {
// Lấy tất cả giá trị
print(Color.values); // [Color.red, Color.green, Color.blue]
// Index
print(Color.red.index); // 0
print(Color.green.index); // 1
// Name
print(Color.red.name); // red
}4. Sử dụng trong switch
enum Status { pending, approved, rejected }
void handleStatus(Status status) {
switch (status) {
case Status.pending:
print('Đang chờ xử lý');
break;
case Status.approved:
print('Đã duyệt');
break;
case Status.rejected:
print('Từ chối');
break;
}
}5. Enhanced Enums (Dart 2.17+)
enum Vehicle {
car(wheels: 4, maxSpeed: 200),
bike(wheels: 2, maxSpeed: 120),
truck(wheels: 6, maxSpeed: 100);
final int wheels;
final int maxSpeed;
const Vehicle({required this.wheels, required this.maxSpeed});
String get description => '$name has $wheels wheels';
}
void main() {
print(Vehicle.car.wheels); // 4
print(Vehicle.bike.description); // bike has 2 wheels
}6. Enum với methods
enum Priority {
low(1),
medium(2),
high(3),
critical(4);
final int level;
const Priority(this.level);
bool isHigherThan(Priority other) => level > other.level;
String get emoji {
switch (this) {
case Priority.low: return '🟢';
case Priority.medium: return '🟡';
case Priority.high: return '🟠';
case Priority.critical: return '🔴';
}
}
}7. Enum implement interface
abstract class Describable {
String describe();
}
enum PizzaSize implements Describable {
small(8),
medium(12),
large(16);
final int inches;
const PizzaSize(this.inches);
@override
String describe() => '$name ($inches inches)';
}8. Parse String to Enum
enum Color { red, green, blue }
void main() {
// String to Enum
String colorName = 'red';
Color color = Color.values.firstWhere(
(e) => e.name == colorName,
orElse: () => Color.red,
);
// Hoặc với Dart 2.17+
Color? parsed = Color.values.asNameMap()[colorName];
}📝 Tóm tắt
- Enum định nghĩa tập hằng số có tên
.valueslấy tất cả giá trị.indexlấy vị trí,.namelấy tên- Enhanced enums có thể có fields và methods
- Phù hợp cho switch-case exhaustive
Last updated on