Dart 2.17 增加了对枚举成员变量的支持,推荐使用方式三
使用dart工具来运行代码,工具:https://dartpad.cn
Dart
//方式一:未支持扩展枚举时
enum InOutOrderStatusEnum {
approval,
completed,
cancel,
rejected;
int get statusCode {
switch (this) {
case InOutOrderStatusEnum.approval:
return 1;
case InOutOrderStatusEnum.completed:
return 2;
case InOutOrderStatusEnum.cancel:
return 3;
case InOutOrderStatusEnum.rejected:
return 4;
}
}
String get statusName {
switch (this) {
case InOutOrderStatusEnum.approval:
return "审批中";
case InOutOrderStatusEnum.completed:
return "已完成";
case InOutOrderStatusEnum.cancel:
return "已撤销";
case InOutOrderStatusEnum.rejected:
return "已拒绝";
}
}
}
//方式二:使用extension对方式一进行优化
enum InOutOrderStatusEnum1 {
approval,
completed,
cancel,
rejected,
}
extension InOutOrderStatusEnumExtension on InOutOrderStatusEnum1 {
int get statusCode => index + 1;
String get statusName => ["审批中", "已完成", "已撤销", "已拒绝"][index];
}
//方式三:Dart 2.17 增加了对枚举成员变量的支持
enum InOutOrderStatusEnum2 {
approval(1, "审批中"),
completed(2, "已完成"),
cancel(3, "已撤销"),
rejected(4, "已拒绝");
final int statusCode;
final String statusName;
const InOutOrderStatusEnum2(this.statusCode, this.statusName);
//想要支持从枚举转换为 String,我们可以很简单地覆写 toString 方法,因为 enums 也继承自 Object
@override
String toString() => 'the $name InOutOrderStatusEnum2 is $statusName';
}
void main() {
final status = InOutOrderStatusEnum.approval;
print(
'statusIndex:${status.index},\n statusCode:${status.statusCode},statusName:${status.statusName}');
final status1 = InOutOrderStatusEnum1.approval;
print(
'statusIndex1:${status1.index},\n statusCode1:${status1.statusCode},statusName1:${status1.statusName}');
final status2 = InOutOrderStatusEnum2.approval;
print(
'status2:$status2,\n statusCode2:${status2.statusCode},statusName2:${status2.statusName}');
}
运行结果: