109

Does Dart support enumerations? For instance:

enum myFruitEnum { Apple, Banana }

A cursory search of the docs suggests no.

Piper
  • 1,266
  • 3
  • 15
  • 26
BraveNewMath
  • 8,090
  • 5
  • 46
  • 51

8 Answers8

174

Beginning 1.8, you can use enums like this:

enum Fruit {
  apple, banana
}

main() {
  var a = Fruit.apple;
  switch (a) {
    case Fruit.apple:
      print('it is an apple');
      break;
  }

  // get all the values of the enums
  for (List<Fruit> value in Fruit.values) {
    print(value);
  }

  // get the second value
  print(Fruit.values[1]);
}

The old approach before 1.8:

class Fruit {
  static const APPLE = const Fruit._(0);
  static const BANANA = const Fruit._(1);

  static get values => [APPLE, BANANA];

  final int value;

  const Fruit._(this.value);
}

Those static constants within the class are compile time constants, and this class can now be used in, for example, switch statements:

var a = Fruit.APPLE;
switch (a) {
  case Fruit.APPLE:
    print('Yes!');
    break;
}
nbro
  • 15,395
  • 32
  • 113
  • 196
Kai Sellgren
  • 27,954
  • 10
  • 75
  • 87
  • 1
    Using `const` is not always possible (if the enum is built with attributes that can not be `const`). That's why I didn't use it in my answer (although I sometimes use `const` enum in my code). – Alexandre Ardhuin Dec 16 '12 at 14:14
  • i will be accepting this answer because it certainly will be useful to use the psuedo enum type in a switch statement – BraveNewMath Dec 16 '12 at 18:56
  • Is there a way to get the String value of the enumerated item? I think static fields will be a better way to go till enums are fully supported if not. – BraveNewMath Dec 17 '12 at 12:37
  • @BraveNewMath What do you mean by "String value of the enumerated item"? Can you give me an example of what you are trying to achieve with this string? – Kai Sellgren Dec 17 '12 at 16:04
  • for example, I want to extract the word Apple from the innumeration. see http://stackoverflow.com/a/13914679/551811 . I think using this approach is less verbose and more intuitive – BraveNewMath Dec 18 '12 at 17:08
  • 2
    @KaiSellgren Note I think the style guide has now changed, so the enum values should be lower camel case instead of all caps. See https://www.dartlang.org/articles/style-guide/#prefer-using-lowercamelcase-for-constant-names – Greg Lowe Nov 30 '14 at 09:17
  • Do you know how to use the experimental enums in 1.8? When I try `pub serve` I get `Experimental language feature 'enums' is not supported. Use option '--enable-enum' to use enum declarations.` Adding that is not a valid option and I couldn't find documentation anywhere... Thx. PS: I am not using the 'official' Dart Editor. – isaacbernat Dec 13 '14 at 14:34
  • 2
    What's`List value`? – Tom Russell Dec 09 '16 at 22:17
  • 2
    You probably meant to write `for (Fruit value in Fruit.values)`, otherwise Dart shows an error – illright Dec 31 '18 at 15:45
9

With r41815 Dart got native Enum support see http://dartbug.com/21416 and can be used like

enum Status {
  none,
  running,
  stopped,
  paused
}

void main() {
  print(Status.values);
  Status.values.forEach((v) => print('value: $v, index: ${v.index}'));
  print('running: ${Status.running}, ${Status.running.index}');
  print('running index: ${Status.values[1]}');
}

[Status.none, Status.running, Status.stopped, Status.paused]
value: Status.none, index: 0
value: Status.running, index: 1
value: Status.stopped, index: 2
value: Status.paused, index: 3
running: Status.running, 1
running index: Status.running

A limitation is that it is not possibly to set custom values for an enum item, they are automatically numbered.

More details at in this draft https://www.dartlang.org/docs/spec/EnumsTC52draft.pdf

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • User Enum with extensions it will solve all the problems https://arkapp.medium.com/supercharge-enum-with-extensions-in-flutter-abf8fdf706fe – abdul rehman Jun 28 '22 at 12:51
5

Enumeration should be available in the future. But until Enum has landed you can do something like :

class Fruit {
  static final APPLE = new Fruit._();
  static final BANANA = new Fruit._();

  static get values => [APPLE, BANANA];

  Fruit._();
}
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
4

This and this may be the answers on your question:

... for the technology preview it was decided to leave it out and just 
use static final fields for now. It may be added later.

You can still do something like this:

interface ConnectionState { }
class Connected implements ConnectionState { }
class Connecting implements ConnectionState { }
class Disconnected implements ConnectionState { }

//later
ConnectionState connectionState;
if (connectionState is Connecting) { ... }

wich is in my opinion more clear for use. It's a bit more difficult for programming the application structure, but in some cases, it's better and clear.

user35443
  • 6,309
  • 12
  • 52
  • 75
  • I think for this example, it would be better to leave out the interface and use a class. Interface is an optional abstraction and – BraveNewMath Dec 17 '12 at 12:46
2

how about this approach:

class FruitEnums {
  static const String Apple = "Apple";
  static const String Banana = "Banana";
}

class EnumUsageExample {

  void DoSomething(){

    var fruit = FruitEnums.Apple;
    String message;
    switch(fruit){
      case(FruitEnums.Apple):
        message = "Now slicing $fruit.";
        break;
      default:
        message = "Now slicing $fruit via default case.";
        break;
    }
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
BraveNewMath
  • 8,090
  • 5
  • 46
  • 51
  • 2
    I wouldn't do it like this myself. I would keep the name in uppercase as `Fruit.APPLE`. Then if I wanted textual output, I would have a map that translates them or some language support separately if I wanted to support other languages as well. I also think `switch` statements work best on integers, because then they can be compiled down to a jump table. – Kai Sellgren Dec 19 '12 at 14:20
1

Yes! Its actually very useful to do Enums in Dart:

  enum fruits{
    banana, apple, orange
  }

Edited by Pete Alvin's comment!

0

Just use Types Class File.

Dart-Types

easy, fast, more powerful and more helpful.

little problem, it is this class limited to five Different Choice and plus one for acts as null.

NabilJaran
  • 39
  • 7
0

In case of anybody still searching for a quick solution for this.

We sometimes need integer value for an enum , sometimes string value. So we implement a quick package for this. Enum Value Generator and an extension to easly generate necessary codes but this is not mandatory.vscode extension. It is also capable of use with jsonAnnotation too.

import 'package:mobkit_generator/annotations.dart';

part 'example.g.dart'

@EnumSerializable(String)
enum PersonStr {
  @EnumValue('John')
  name,
  @EnumValue('66')
  number,
}

@EnumSerializable(int)
enum PersonInt {
  @EnumValue(1)
  name,
  @EnumValue('66')
  number,
}
BarisY
  • 151
  • 1
  • 5