枚举类型,通常称为枚举或枚举,是一种特殊的类,用于表示固定数量的常量值。
定义一个简单的枚举
关键字都是一样的
dart
enum Color { red, green, blue }
可以以,结尾以便利于复制,而不会产生问题
dart
enum Color { red, green, blue ,}
void main() {
print(Color.values.length);//3
}
定义一个增强枚举
Dart还允许enum声明使用字段、方法和const构造函数来声明类,这些构造函数限制为固定数量的已知常量实例。
声明增强型枚举时,遵循与普通类类似的语法,但有一些额外要求:
实例变量必须是 final,包括由 mixin 添加的变量
所有生成式构造函数必须是 const
工厂构造函数只能返回固定的、已知的枚举实例之一
不能继承其他类,因为 Enum 会自动被继承
不能重写 index、hashCode 或相等运算符 ==
不能在枚举中声明名为 values 的成员,因为它会与自动生成的静态 values getter 冲突
枚举的所有实例必须在声明开头声明,并且必须至少声明一个实例
增强枚举中的实例方法可以使用this来引用当前枚举值。
dart
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;
}
增强枚举最低要求2.17的语言版本
如何使用枚举
枚举的访问也和java一样
dart
final favoriteColor = Color.blue;
if (favoriteColor == Color.blue) {
print('Your favorite color is blue!');
}
每个枚举都有下标值,也是从0开始
dart
assert(Color.red.index == 0);
assert(Color.green.index == 1);
assert(Color.blue.index == 2);
要获取所有枚举值的列表,请使用.value
dart
List<Color> colors = Color.values;
assert(colors[2] == Color.blue);
你可以在switch中使用枚举,如果你没有考虑到所有的分支
,将会报错,你也可以使用default或者case _,
如果你对switch还不了解,可以看看之前的文章 dart 分支
dart
var aColor = Color.blue;
switch (aColor) {
case Color.red:
print('Red as roses!');
case Color.green:
print('Green as grass!');
default: // Without this, you see a WARNING.
print(aColor); // 'Color.blue'
}
如果您需要访问枚举值的名称,可以使用.name
dart
print(Color.blue.name); // 'blue'
你同样可以访问枚举对象的成员,和访问对象一样
dart
print(Vehicle.car.carbonFootprint);