Table of contents
Enum :
An enum is a special type that represents a fixed number of constant values.
An enum is declared using the keyword enum followed by the enum’s name.
enum Color {
red,
green,
blue,
}
extension ColorExtension on Color {
String get displayName {
switch (this) {
case Color.red:
return 'Red';
case Color.green:
return 'Green';
case Color.blue:
return 'Blue';
default:
throw ArgumentError('Unknown color: $this');
}
}
// You can define other methods or properties here
}
void main() {
print(Color.red.displayName); // Output: Red
}
Enumerations :
Enumerated types (also known as enumerations or enums) are primarily used to define named constant values.
The enum keyword is used to define an enumeration type in Dart.
The use case of enumeration is to store finite data members under the same type definition.
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;
}
void main() {
var vehicleList = [Vehicle.bus, Vehicle.car, Vehicle.bicycle];
print('Before sorting:\n${vehicleList.join('\n')}\n');
}