Dart. Enum with arguments

Viewed 581

Is it possible to create enum with arguments. For example in Kotlin I can do something like this:

  enum class TestType(val testText: String, val number: Int) {
        STATIC("", 0),
        DYNAMIC("", 1)
    }

And each enum item contains testText and number. Is it possible to implement this in the Dart programming language. Please help me.

3 Answers

Dart 2.17 enhanced functionality provide way to add arguments in enums,

Example:

enum TestType {
   STATIC("", 0),
   DYNAMIC("", 1);

  const TestType(this.text, this.value);
  final String text;
  final int value;
}

To use it:

void main() {
  const testType = TestType.STATIC;
  print(testType.value); // 0
}

Note: To enable this functionality, need to modify pubspec dart version to 2.17 like

environment:
  sdk: ">=2.17.0 <3.0.0"

You can certainly build one with an ordinary class and a lot of static const for the values. The only thing you'll be missing from a proper enum is ensuring all cases are covered in a switch.

Related