Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

enums - Does Dart support enumerations?

Does Dart support enumerations? For instance:

enum myFruitEnum { Apple, Banana }

A cursory search of the docs suggests no.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...