dart enum
Enumeration in dart

Hi Guys, Welcome to Proto Coders Point. In this Dart Tutorial, we will learn what is enumeration in dart, what does enumeration means & how to use enum in dart programming language & when to use enums.

What is enum in dart

A dart enum is basically a list of named constant values. In dart program enum keyword is used to define enumeration type in dart.

In dart enum is been used to define a collection of constant.

Syntax:

enum enum_name{
  
   constant value 1,   // data member 1
   constant value 2,
   constant value 3,

}

Let’s analysis the above syntax of enum:

  • enum: A enum keyword is used to initialize enumerated data type.
  • enum_name: is a user given name for enum class, is used for naming convension of enumerated class.
  • constant(data member): constant value of enum class & should be seperated by “,” commas.

note: enum class last data member will not have a comma.


When to use enums

As you known enum are list of constants value & is used when you know all the const value at development time.

Where to use enum -> common example suppose you want to a show week days name “MONDAY – SUNDAY” in a dropdown menu at that time you know week days data is constant and will never change.

Enum Dart Code Example Below

Example 1 -> Iterate through enum & print enum class value

enum Fruits{
  mango,
  apple,
  banana,
  grapes
}
void main(){

     for(Fruits name in Fruits.values)
    {
        print(name);
     }
}

Example 2 -> Enum Switch Case Statement

enum Fruits {
  apple,
  mango,
  banana,
  grapes
}
 
void main() { 
   
  // Assign a value from
  // enum to a variable geek
  // assume you app user will select from Menu Item Fruits
  var selectedEnumFruit = Fruits.Banana;
   
  // Switch-case
  switch(selectedEnumFruit) {
    case Fruits.apple: print("You selected Apple");
    break;
    case Fruits.mango: print("You selected mango");
    break;
    case Fruits.banana: print("You selected Banana");
    break;
    case Fruits.grapes: print("You selected Grapes");
    break;
  }
}

Note: The enumeration data is stores a string value without any quatation mark, as normal string data has ” “.


Example 3: Animated Button Loading Indicator using Enum

Check out this article, I created 3 state on a button with animation effect (initial State, Loading, Completed) using Dart enum