How to assign raw value to enum in Dart?

Viewed 800

In Swift, you can easily assign raw value to enum, eg:

enum Game: Int {
    case lol = 1
    case dnf = 2
    case dota = 3
}

However, you can't assign raw value to enum in Dart:

enum Game {
  lol = 1,
  dnf = 2,
  dota = 3,
}

It's showed error and you can only use the simplest enum:

enum Game {
  lol,
  dnf,
  dota,
}

It's really let me down.

Any way assign raw value to Dart's enum like Swift?

3 Answers

You can use enum extensions for example

enum EnumAction { subtract, add }

extension EnumActionExtension on EnumAction {
  String get name {
    switch (this) {
      case EnumAction.add:
        return 'add';
      case EnumAction.subtract:
        return 'subtract';
    }
  }
}

In your case you would return an int and an int value. Enums also have int values assigned to them by default, their respective index. You could call Game.lol.index and it would return 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 Game {
    lol,
    dnf,
    dota;
  int get intValue => index + 1;
}

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 an enum value of type Game will have a getter intValue that returns the int values mentioned in the question, so print(myGame.intValue) will print 1, 2, or 3.

Dart 2.17 support enhanced enum

enum Game {
  lol(1),
  dnf(2),
  dota(3);
  
  const Game(this.value);
  final int value;
}

Use it like:

void main() {
  const game = Game.lol;
  print(game.value); // 1
}
Related