17.7 C
New York
Thursday, September 29, 2022

Flutter & Dart: ENUM Example

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.Advertisements

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.

Advertisements

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles