DEV Community

Safal Shrestha
Safal Shrestha

Posted on

Dart enhanced enum with custom values

An enum type is a special data type that enables for a variable to be a set of predefined constants. It helps to make code readable and easier to understand.

For example, you might use an enum to define the gender of the people, like this:

enum Gender{
  Male,
  Female,
  Other
}
Enter fullscreen mode Exit fullscreen mode

Now if you run the following code

void main() {
  print(Gender.Female.index);          // 1
  print(Gender.Male.index);            // 0
  print(Gender.Male);                  //Gender.Male
  print(Gender.values[2]);             //Gender.Other
}
Enter fullscreen mode Exit fullscreen mode

We can access index *of the element defined and element using the *index.

Now what if we want to define custom value to the element of our enum. What if we want to assign number 1 to Male, 2 to Female and null to Other, and what if we want to return element of enum from the values that we defined for the element?

How can we do so ?

enum Gender {
  Male(1),
  Female(2),
  Other(null);
  const Gender(this.number);
  final int? number;
  static Gender getByValue(int? i) {
    return Gender.values.firstWhere((element) => element.number == i);
  }
}

void main() {
  print(Gender.getByValue(1));    //Gender.Male 
  print(Gender.getByValue(2));    //Gender.Female
  print(Gender.getByValue(3));    //Uncaught Error: Bad state: No element
  print(Gender.getByValue(null)); //Gender.Other
  print(Gender.Other.number);     //null
  print(Gender.Female.index);     //1
  print(Gender.values[2]);        //Gender.Other
}
Enter fullscreen mode Exit fullscreen mode

In the above code snippet, we defined our values to the element of the the enum Gender. So, we can access the element of enum using the values we defined and vice versa. We can also access element using index and values like before. To use the values we defined, we can use the function getByValue that we created and number variable we defined.

Thanks for Reading! ✌️

Top comments (0)