Enum from String

前端 未结 18 2034
温柔的废话
温柔的废话 2020-12-15 14:54

I have an Enum and a function to create it from a String because i couldn\'t find a built in way to do it



        
18条回答
  •  温柔的废话
    2020-12-15 15:33

    I improved Collin Jackson's answer using Dart 2.7 Extension Methods to make it more elegant.

    enum Fruit { apple, banana }
    
    extension EnumParser on String {
      Fruit toFruit() {
        return Fruit.values.firstWhere(
            (e) => e.toString().toLowerCase() == 'fruit.$this'.toLowerCase(),
            orElse: () => null); //return null if not found
      }
    }
    
    main() {
      Fruit apple = 'apple'.toFruit();
      assert(apple == Fruit.apple); //true
    }
    

提交回复
热议问题