Open In App

Data Enumeration in Dart

Last Updated : 11 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Syntax:
enum variable_name{
  // Insert the data members as shown
  member1, member2, member3, ...., memberN
}

Let’s analyze the above syntax:

  1. The enum is the keyword used to initialize enumerated data type.
  2. The variable_name as the name suggests is used for naming the enumerated class. 
  3. The data members inside the enumerated class must be separated by the commas.
  4. Each data member is assigned an integer greater than then the previous one, starting with 0 (by default).
  5. Make sure not to use semi-colon or comma at the end of the last data member.

Example 1: Printing all the elements from the enum data class.  

Dart




// dart program to print all the
// elements from the enum data class
 
// Creating enum with name Gfg
enum Gfg {
   
  // Inserting data
  Welcome, to, GeeksForGeeks
}
 
void main() {
   
  // Printing the value
  // present in the Gfg
  for (Gfg geek in Gfg.values) {
    print(geek);
  }
}


Output:   

Gfg.Welcome
Gfg.to
Gfg.GeeksForGeeks

Note: Notice in the above example the strings are not enclosed with quotes, so that it can be used to print different results by comparing them with the values inside the enum. 

Example 2: Using switch-case to print result. 

Dart




enum Gfg {
  Welcome, to, GeeksForGeeks
}
 
void main() { 
   
  // Assign a value from
  // enum to a variable geek
  var geek = Gfg.GeeksForGeeks;
   
  // Switch-case
  switch(geek) {
    case Gfg.Welcome: print("This is not the correct case.");
    break;
    case Gfg.to: print("This is not the correct case.");
    break;
    case Gfg.GeeksForGeeks: print("This is the correct case.");
    break;
  }
}


Output:  

This is the correct case. 

Note: The enumerated class does not hold all types of data, rather it stores only string values without the quotes over them.
  
Limitation of Enumerated Data Type:   

  1. It cannot be subclassed or mixed in.
  2. It is not possible to explicitly instantiate an enum.
     


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads