4

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
  • 3,093
  • 1
  • 18
  • 29

2 Answers2

4

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];
}
Mustafa yıldiz
  • 325
  • 1
  • 8
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
  • 804
  • 7
  • 3
  • unfortunately as of now the properties can not be treated as constant values – Sergio G Aug 06 '23 at 02:42
  • 1
    Sergio, I think you are referring to the fact that the properties of an enum is not a constant expression, for example: ```dart enum ErrorCode { none(0), unknown(1), connectionLost(100), outlierReading(200); final int value; const ErrorCode(this.value); } const c1 = ErrorCode.none; const c2 = ErrorCode.none.value; // Error, not a constant value. ``` Please check out https://github.com/dart-lang/language/issues/2780 for further discussions about this topic. – Erik Ernst Aug 24 '23 at 19:29
  • exactly that, thanks for sending the reference to this particular issue – Sergio G Aug 27 '23 at 15:54