Flutter & Dart: ENUM Example

Last updated on July 18, 2021 The Frog Loading... Post a comment

This article shows you how to use enumerations (also known as enums or enumerated types) in Dart and Flutter.

Overview

An enumeration in Dart is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.

An enumeration can be declared by using the enum keyword:

enum Aniaml {dog, cat, chicken, dragon}

Every value of an enumeration has an index. The first value has an index of 0.

You can retrieve all values of an enumeration by using the values constant:

print(Aniaml.values);
// [Aniaml.dog, Aniaml.cat, Aniaml.chicken, Aniaml.dragon]

A Complete Example

The code:

// Declare enum
enum Gender {
  Male,
  Female
}

// Make a class
class Person {
  final String name;
  final int age;
  final Gender gender;
  
  Person(this.name, this.age, this.gender); 
}

// Create an instance
final personA = Person("John Doe", 40, Gender.Male); 

void main(){
  if(personA.gender == Gender.Male){
    print("Hello gentleman!");
  } else {
    print("Hello lady!");
  }
}

Output:

Hello gentleman!

What’s Next?

You’ve learned the fundamentals of enumerations in Dart and Flutter. Continue exploring more new and interesting stuff by taking a look at the following articles:

You can also check out our Flutter category page, or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles