Home > Net >  What's the best use case of enum value in dart?
What's the best use case of enum value in dart?

Time:09-13

I want to know the major use cases with example will be great.

CodePudding user response:

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.

example:

enum day {
  sunday,
  monday,
  tuesday,
  wednesday,
  thursday,
  friday,
  saturday,
}
    void main() { 

  // assume you app user will select from Menu Item day
   var selectedEnumDay = day.friday;
   
  // Switch-case
   switch(selectedEnumDay) {
    case day.sunday: print("You selected sunday");
    break;
    case day.monday: print("You selected monday");
    break;
    case day.tuesday: print("You selected tuesday");
    break;
    case day.wednesday: print("You selected wednesday");
    break;
    case day.thursday: print("You selected thursday");
    break;
    case day.friday: print("You selected friday");
    break;
    case day.saturday: print("You selected saturday");
    break;
  }
}

CodePudding user response:

Enum are a special type of class that allow creating a set of constant values associated with a particular type. [ 1 ]


Enums are great for representing a discrete set of states. [ 2 ]

one of simple example using enum is :

enum RequestState {success, error, notAsked, loading }

...
RequestState apiState = RequestState.notAsked;


  Widget buildContaier() {
    switch(apiState){
       case apiState.loading:
           return CircularProgressIndicator();
       case apiState.success:
           return ListView();
       case apiState.error:
           return Text("error fetch api");
       default:
           return Container();
   }
  • Related