Enum In Dart/Flutter

Table of contents

No heading

No headings in the article.

When programming with Dart/Flutter, at least a few times we have worked with enum, and you are no stranger to enum. But the following usage can help your code cleaner and use them more easily.

Let's get started!

Let's create enums:

enum StatusEnum {completed, cancel, pending}

For example, I want to set the color for each StatusEnum to use in the UI display:

completed //Colors.green
cancel //Colors.red
pending //Colors.blue

If you don't know this way, usually we will use switch/case to return the color of each StatusEnum.

Color getColorStatusEnum(StatusEnum statusEnum){
    switch(statusEnum){
      case StatusEnum.completed:
            return Colors.green;
            ...

    }
}

But I will show you a faster and more convenient way. We will use the extension with StatusEnum:

extension StatusEnumExt on StatusEnum {

  Color get color =>[Colors.green, Colors.cancel, Colors.blue][index]
  //It will point to each corresponding enum index to retrieve the desired colors.

}

and the rest is that you just need to use it normally.

...
  Text('Completed', style: TextStyle(color : StatusEnum.completed.color)
...

Also you can create as many values ​​as you want this way, for example the title of StatusEnum:

extension StatusEnumExt on StatusEnum {

  Color get color =>[Colors.green, Colors.cancel, Colors.blue][index]

  Color get title =>['Completed ', 'Cancel', 'Pending'][index]

}

and use it above

...
  Text(StatusEnum.completed.title, style: TextStyle(color : StatusEnum.completed.color) //Completed
...

If you have any questions, you can comment and I will answer as soon as possible. Thank you for reading.