Add methods or values to enum in dart

前端 未结 8 965
刺人心
刺人心 2020-12-14 05:21

In java when you are defining an enum you can do something similar to the following. Is this possible in Dart?

enum blah {
  one(1), two(2);
  final num valu         


        
8条回答
  •  隐瞒了意图╮
    2020-12-14 06:10

    As an improvement on the other suggestions of using Extensions, you can define your assigned values in a list of map, and the extension will be concise.

    enum Numbers {
      one,
      two,
      three,
    }
    
    // Numbers.one.value == 1
    

    example with list

    extension NumbersExtensionList on Numbers {
      static const values = [1, 2, 3];
      int get value => values[this.index];
    }
    

    example with map

    extension NumbersExtensionMap on Numbers {
      static const valueMap = const {
        Numbers.one: 1,
        Numbers.two: 2,
        Numbers.three: 2,
      };
      int get value => valueMap[this];
    }
    

    Note: This approach has the limitation that you can not define a static factory method on the Enum, e.g. Numbers.create(1) (as of Dart 2.9). You can define this method on the NumbersExtension, but it would need to be called like NumbersExtension.create(1)

提交回复
热议问题