3

The only thing I can find to set the enum value is this: Add methods or values to enum in dart

However, I find it a bit tedious. Is there a better way?

In C# I can just simply do something like this:

enum ErrorCode
{
    None = 0,
    Unknown = 1,
    ConnectionLost = 100,
    OutlierReading = 200
}
Visual Sharp
  • 2,368
  • 1
  • 8
  • 24

2 Answers2

3

Here is the simple exapmle

enum ErrorCode {
  None,
  Unknown,
  ConnectionLost,
  OutlierReading,
}

extension ErrorCodeExtention on ErrorCode {
  static final values = {
    ErrorCode.None: 0,
    ErrorCode.Unknown: 1,
    ErrorCode.ConnectionLost: 100,
    ErrorCode.OutlierReading: 200,
  };

  int? get value => values[this];
}
0

There's an upcoming feature in Dart known as enhanced enums, and it allows for enum declarations with many of the features known from classes. For example:

enum ErrorCode {
    None(0),
    Unknown(1),
    ConnectionLost(100),
    OutlierReading(200);
  final int value;
  const ErrorCode(this.value);
}

The feature is not yet released (and note that several things are not yet working), but experiments with it can be performed with a suitably fresh version of the tools by passing --enable-experiment=enhanced-enums.

The outcome is that ErrorCode is an enum declaration with four values ErrorCode.None, ErrorCode.Unknown, and so on, and we have ErrorCode.None.value == 0 and ErrorCode.Unknown.value == 1, and so on. The current bleeding edge handles this example in the common front end (so dart and dart2js will handle it), but it is not yet handled by the analyzer.

Erik Ernst
  • 634
  • 4
  • 3