flutter中枚举的使用

枚举支持成员属性、实现和定义方法,使用时需要注意的地方:

  • 枚举的所有实例都必须在声明的开头声明,并且必须至少声明一个实例
  • 最后一个枚举元素以 ; 结尾,其余的枚举元素以 ,结尾。
  • 枚举的构造函数 一定要是 const 构造
  • 枚举中的三个属性:index、values和name

如下代码示例:推荐使用方式三 

使用dart工具来运行代码,工具:https://dartpad.cn

//方式一:未支持扩展枚举时
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(
      '\n statusIndex2:${status2.index},\n statusValues:${InOutOrderStatusEnum2.values}\n statusCode2:${status2.statusCode},statusName2:${status2.statusName}');
}

运行结果:

statusIndex:0, statusCode:1,statusName:审批中

statusIndex1:0, statusCode1:1,statusName1:审批中

statusIndex2:0, statusValues:[InOutOrderStatusEnum2.approval, InOutOrderStatusEnum2.completed, InOutOrderStatusEnum2.cancel, InOutOrderStatusEnum2.rejected] statusCode2:1,statusName2:审批中

参考:Dart(15)-枚举_dart enum-CSDN博客 

你可能感兴趣的:(flutter,flutter)