美文网首页
dart枚举实现

dart枚举实现

作者: follow_er | 来源:发表于2021-06-10 20:37 被阅读0次

    dart 枚举不能自定义初始值,但是Dart2.7 支持了扩展枚举。我们先写一个枚举值。

    enum ColorType {
      red,
      green,
      blue
    }
    

    枚举值是一个类, 给这个类添加一个静态方法,getTypeValue,传入从服务器端获取的int值来兑成枚举值。
    然后我们让red = 10 ,green = 20, blue = 30.

    extension ColorTypeExtension on ColorType  {
    
       static ColorType getTypeValue(int index) {
        switch (index) {
          case 10:
            return ColorType.red;
            break;
          case 20:
            return ColorType.green;
            break;
          case 30:
            return ColorType.blue;
            break;
        }
      }
    

    定义完枚举之后,可以进行测试,这样如果少枚举值,没有写default情况就会报警告⚠️

      void _test() {
        int currentColor = 20;//ColorType.red;
        ColorType color = ColorTypeExtension.getTypeValue(currentColor);
        switch (color) {
          case ColorType.red:
            print('index:' + color.index.toString());//'red:' + currentColor.statusCode.toString() +
            break;
          case ColorType.green:
            print('green...');
            break;
          case  ColorType.blue:
            print('blue...');
            break;
            default : //如果不写default报枚举值会报警告
            break;
        }
    

    相关文章

      网友评论

          本文标题:dart枚举实现

          本文链接:https://www.haomeiwen.com/subject/ptypeltx.html