Android学Dart学习笔记第二十节 类-枚举

枚举类型,通常称为枚举或枚举,是一种特殊的类,用于表示固定数量的常量值。

定义一个简单的枚举

关键字都是一样的

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);
相关推荐
砖厂小工6 小时前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心6 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心6 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
shankss7 小时前
Flutter 下拉刷新库 pull_to_refresh_plus 设计与实现分析
flutter
Kapaseker9 小时前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴9 小时前
Android17 为什么重写 MessageQueue
android
忆江南1 天前
iOS 深度解析
flutter·ios
明君879971 天前
Flutter 实现 AI 聊天页面 —— 记一次 Markdown 数学公式显示的踩坑之旅
前端·flutter
恋猫de小郭1 天前
移动端开发稳了?AI 目前还无法取代客户端开发,小红书的论文告诉你数据
前端·flutter·ai编程
MakeZero1 天前
Flutter那些事-交互式组件
flutter