flutterdartenumsjson-valuejson-annotation

Is it possible to define enum with same jsonValue() in Dart?


Can I define enum like this?: what is the best way to handle different type values with the same key like this:

enum type{
  @JsonValue(0)
  @JsonValue(1)
  @JsonValue(3)
  @JsonValue(9)
  @JsonValue(10)
  @JsonValue(11)
  @JsonValue(12)
  add,
  @JsonValue(2)
  @JsonValue(4)
  @JsonValue(5)
  @JsonValue(6)
  @JsonValue(7)
  @JsonValue(8)
  sub,
}```

Solution

  • I don't think you got a direct way to handle this through json_serializable ; but that doesn't mean there aren't workarounds.

    Seeing how you got the possibility of defining functions directly in enums now (Though you could already do it before with extensions), you could have a simple enum be created from your seralized Json, and have an easy way to convert this enum to your add/sub one through a getter :

    enum TransitionEnum {
      add0,
      add1,
      sub2,
      add3,
      sub4,
      sub5,
      sub6,
      sub7,
      sub8,
      add9,
      add10,
      add11,
      add12;
    
      RealValue get realValue {
        switch (this) {
          case TransitionEnum.add0:
          case TransitionEnum.add1:
          case TransitionEnum.add3:
          case TransitionEnum.add9:
          case TransitionEnum.add10:
          case TransitionEnum.add11:
          case TransitionEnum.add12:
            return RealValue.add;
    
          case TransitionEnum.sub2:
          case TransitionEnum.sub4:
          case TransitionEnum.sub5:
          case TransitionEnum.sub6:
          case TransitionEnum.sub7:
          case TransitionEnum.sub8:
            return RealValue.sub;
        }
      }
    }
    
    enum RealValue {
      add,
      sub,
    }
    

    Quick DartPad demo: https://dartpad.dev/?id=552b5451435178bb4af2ca40a07888dc