Dart – How to loop an enum

Dart provides .values to get list of values in an enum. Since it is a list, we can use any method of List data type.

In this post we make a demo to loop through all the values of an enum.

enum Animal { Dog, Cat, Chicken, Elephant }

void main() {
  Animal.values.forEach((name) {
    print(name);
  });
}

Output:

Animal.Dog
Animal.Cat
Animal.Chicken
Animal.Elephant


In case you want to print just the name (Dog, Cat, Chicken, Elephant), you can do one more step like below:

enum Animal { Dog, Cat, Chicken, Elephant }

void main() {
  Animal.values.forEach((name) {
    print(name?.toString()?.split('.')?.elementAt(1));
  });
}


Output:

Dog
Cat
Chicken
Elephant

If you are looking for mobile/web Software Engineers to build you next projects, please Drop us your request!

Tagged : / /
Subscribe
Notify of
guest

2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
abin
3 years ago

how do you delete the “Animal.” ?

2
0
Would love your thoughts, please comment.x
()
x