Introduction
In our day-to-day lives, there are multiple values we consider constants. Generally, certain terms like a dozen are treated as constant and hold a predefined value in our minds. Similarly, in mathematics, the value of pi, which is equal to 3.14, is a well-defined constant. In many cases, it is convenient for us to define certain constants that help us in our day-to-day work.
Dart allows us to define constant values with the help of enumerations or enums. They are significantly used to define named constant values. Enum Keyword is used to declare an enumerated data type.
Now, since we have a brief overview of the topic, let us elaborate more on it and increase our understanding of it.
Declaration of Enums
The syntax for the declaration of enums is :
enum variable_name{
// relevant data members that need to be enlisted
First member, Second Member, Third Member, and so on…...
}
Let us now understand the various keywords used in the writing of the above syntax:
- Enum: This keyword is used for initializing enumerated data types.
- Variable_name: It is used to define the name of the enumerated class.
Following rules must be kept in mind while writing the syntax:
- We should use commas for the separation of various members inside the enumeration class.
- We need to assign subsequent integer values to each data member as we define them. By default, the first member starts from 0.
- No comma or a semi-colon must be used at the end of the last data member in the enumerated class.
Let us now understand dart enums more clearly with the help of an example.
Code:
// dart program to print all the
// elements from the enum data class
// Creating enum with name Gfg
enum Ninja {
// Inserting data
Welcome,
to,
CodingNinjas
}
void main() {
// Printing the value
// present in the Ninja
for (Ninja geek in Ninja.values) {
print(geek);
}
}
Output:
Ninja.Welcome
Ninja.to
Ninja.CodingNinjas
We can also represent enums using a switch block. In this implementation, case- blocks for all enum class is required. We also need to add a default block when case block implementation is missing. If this rule is not complied with, we shall encounter a compilation error in our program. Hence, we can conclude that case blocks are essential in dart enums.
Let’s understand it better with an example program that uses a switch-case:
Code:
enum Ninja { Welcome, to, CodingNinjas }
void main() {
// Assign a value from
// enum to a variable Ninja1
var Ninja1 = Ninja.CodingNinjas;
// Switch-case
switch (Ninja1) {
case Ninja.Welcome:
print("This is not the correct case.");
break;
case Ninja.to:
print("This is not the correct case.");
break;
case Ninja.CodingNinjas:
print("This is the correct case.");
break;
}
}
Output:
This is the correct case.




