What are Enums?
An enum (enumeration) is a type with a fixed set of named constant values. Enums make code more readable and type-safe by replacing magic strings or integers with meaningful names.
Basic Enums
enum Direction { north, south, east, west }
enum Status { active, inactive, pending, banned }
enum Color { red, green, blue }
void main() {
Direction dir = Direction.north;
print(dir); // Direction.north
print(dir.name); // north
print(dir.index); // 0
// All values
print(Direction.values); // [Direction.north, Direction.south, ...]
}
Enhanced Enums (Dart 2.17+)
Dart 2.17+ allows enums to have fields, methods, and constructors:
enum Planet {
mercury(3.7),
venus(8.87),
earth(9.81),
mars(3.72);
final double gravity; // m/s²
const Planet(this.gravity);
double weightOn(double mass) => mass * gravity;
}
void main() {
double myMass = 70.0; // kg on Earth
for (var planet in Planet.values) {
print('Weight on $${planet.name}: '
'$${planet.weightOn(myMass).toStringAsFixed(1)} N');
}
}
Output:Weight on mercury: 259.0 N
Weight on venus: 620.9 N
Weight on earth: 686.7 N
Weight on mars: 260.4 N
Enums in Switch
Status userStatus = Status.pending;
switch (userStatus) {
case Status.active:
print('User is active');
break;
case Status.pending:
print('Awaiting approval');
break;
case Status.banned:
print('Access denied');
break;
default:
print('Unknown status');
}
// Dart 3 pattern matching switch:
String label = switch (userStatus) {
Status.active => 'Active',
Status.inactive => 'Inactive',
Status.pending => 'Pending',
Status.banned => 'Banned',
};
🧠 Quiz
1. What does enum.name return?
- A) The enum type name
- B) The constant name as a String ✅
- C) The index
- D) null
2. Can Dart enums have methods?
- A) No
- B) Yes, since Dart 2.17 ✅
- C) Only static methods
- D) Only in abstract enums
Summary
Enums define a fixed set of named constants. Use enum.name for the string name, enum.index for position, and Enum.values for all constants. Dart 2.17+ enhanced enums support fields, methods, and constructors. Use enums in switch statements for exhaustive pattern matching.