Created
October 14, 2021 09:37
-
-
Save mhmadip/322c2efb7d53b30c44822438e78aa754 to your computer and use it in GitHub Desktop.
Enumerated types Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Enumerated types, often called enumerations or enums, | |
// are a special kind of class used to represent a fixed number of constant values. | |
//Declare an enumerated type using the enum keyword: | |
enum Color { red, green, blue } | |
//To get a list of all of the values in the enum, use the enum’s values constant. | |
List<Color> colors = Color.values; | |
void main() { | |
//You can use trailing commas when declaring an enumerated type. | |
// | |
// Each value in an enum has an index getter, | |
// which returns the zero-based position of the value in the enum declaration. | |
// For example, the first value has index 0, and the second value has index 1. | |
assert(Color.red.index == 0); | |
assert(Color.green.index == 1); | |
assert(Color.blue.index == 2); | |
print(colors); | |
assert(colors[2] == Color.blue); | |
var aColor = Color.blue; | |
//You can use enums in switch statements, | |
// and you’ll get a warning if you don’t handle all of the enum’s values: | |
switch (aColor) { | |
case Color.red: | |
print('Red as roses!'); | |
break; | |
case Color.green: | |
print('Green as grass!'); | |
break; | |
default: // Without this, you see a WARNING. | |
print(aColor); // 'Color.blue' | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment