Does Dart support enumerations? For instance:
enum myFruitEnum { Apple, Banana }
A cursory search of the docs suggests no.
Enumerated types (also known as enumerations or enums) are primarily used to define named constant values. The enum keyword is used to define an enumeration type in Dart. The use case of enumeration is to store finite data members under the same type definition.
Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values to integral constants, that make a program easy to read and maintain.
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.
Enums are still restricted, you cannot implement the interface other than by creating an enum .
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; }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With