xxxxxxxxxx
Syntax
enum enum_name {
enumeration list
}
Where the enum_name specifies the enumeration type name
The enumeration list is a comma-separated list of identifiers
Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0.
Example:
enum Status {
none,
running,
stopped,
paused
}
xxxxxxxxxx
enum Status {
none,
running,
stopped,
paused
}
void main() {
print(Status.values);
Status.values.forEach((v) => print('value: $v, index: ${v.index}'));
print('running: ${Status.running}, ${Status.running.index}');
print('running index: ${Status.values[1]}');
}
xxxxxxxxxx
enum Water {
frozen(32),
lukewarm(100),
boiling(212);
final int value;
const Water(this.value);
}
void main() {
print(Water.value)
}
xxxxxxxxxx
enum Fruit {
apple,
banana,
orange,
}
void main() {
// Accessing enum values
print(Fruit.apple); // Output: Fruit.apple
// Converting enum to a string
print(Fruit.banana.toString()); // Output: Fruit.banana
// Converting a string to an enum value
Fruit selectedFruit = Fruit.orange;
String fruitString = 'apple';
selectedFruit = Fruit.values.firstWhere((fruit) => fruit.toString().split('.').last == fruitString, orElse: () => null);
print(selectedFruit); // Output: Fruit.apple
// Enum iteration
for (var fruit in Fruit.values) {
print(fruit);
}
}
xxxxxxxxxx
enum Vehicle implements Comparable<Vehicle> {
car(tires: 4, passengers: 5, carbonPerKilometer: 400),
bus(tires: 6, passengers: 50, carbonPerKilometer: 800),
bicycle(tires: 2, passengers: 1, carbonPerKilometer: 0);
const Vehicle({
required this.tires,
required this.passengers,
required this.carbonPerKilometer,
});
final int tires;
final int passengers;
final int carbonPerKilometer;
int get carbonFootprint => (carbonPerKilometer / passengers).round();
bool get isTwoWheeled => this == Vehicle.bicycle;
@override
int compareTo(Vehicle other) => carbonFootprint - other.carbonFootprint;
}