Skip to main content

Command Palette

Search for a command to run...

Enums in Dart | Enumerations

Updated
3 min read
Enums in Dart | Enumerations
V

"Hello World, I'm Vinit Mepani, a coding virtuoso driven by passion, fueled by curiosity, and always poised to conquer challenges. Picture me as a digital explorer, navigating through the vast realms of code, forever in pursuit of innovation.

In the enchanting kingdom of algorithms and syntax, I wield my keyboard as a magical wand, casting spells of logic and crafting solutions to digital enigmas. With each line of code, I embark on an odyssey of learning, embracing the ever-evolving landscape of technology.

Eager to decode the secrets of the programming universe, I see challenges not as obstacles but as thrilling quests, opportunities to push boundaries and uncover new dimensions in the realm of possibilities.

In this symphony of zeros and ones, I am Vinit Mepani, a coder by passion, an adventurer in the digital wilderness, and a seeker of knowledge in the enchanting world of code. Join me on this quest, and let's create digital wonders together!"

What is enum? & why it use in dart?

  • Enum are special kind of class to used to represent fixed number of constant value.

  • we use " enum " keyword for this, enum has own body so we must create a body of enum , otherwise it's throw error.

  • In body we have to compulsory pass one value , the body of enum can not be empty.

  • Syntax:

      enum name{
              element1,
              element2,
              element3    
      }
    
    • we must follow some rules when we write enum body ,such as that after every element we must put coma( , ) , expect last element.

    • Every element has own value and by default value start by 0 and after increment one by one.

Example :

enum daysName {
  Sunday,
  Monday,
  Tuesday,
  Wednesday,
  Thrusday,
  Friday,
  Saturday
}

void main() {
      for(daysName x in daysName.values)
      {
          print(x);
      }
}

What Are Enhanced Enums?

Traditionally, enums in Dart have been a way to represent a set of named values. However, Enhanced Enums take this a step further, introducing a class-like structure to enums. This enhancement enables developers to define methods, properties, and behaviors within enums, making them more versatile and feature-rich.

The Shift Towards Class-Like Enums

Enhanced Enums in Dart blur the lines between traditional enums and classes. Instead of being limited to a set of constant values, developers can now imbue enums with functionality. This paradigm shift allows for more expressive and reusable code, aligning enums with the object-oriented nature of Dart.

Features of Dart Enhanced Enums

1. Methods and Behaviors:

Enhanced Enums bring the ability to define methods, making enums more than just a collection of values. This opens up opportunities for encapsulating logic within enum elements, enhancing code organization and readability.

enum Status {
  pending,
  approved,
  rejected,

  // Method in the Enhanced Enum
  String displayStatus() {
    return this.toString().split('.').last;
  }
}

void main() {
  print(Status.pending.displayStatus()); // Outputs: "pending"
}

2. Properties:

With Enhanced Enums, you can attach properties to individual enum values. This can be particularly useful when each enum variant requires additional data.

enum Planet {
  mercury,
  venus,
  earth,
  mars,
  jupiter,
  saturn,
  uranus,
  neptune,

  // Property in the Enhanced Enum
  int get order {
    return this.index + 1;
  }
}

void main() {
  print(Planet.earth.order); // Outputs: 3
}

3. Custom Constructors:

Enhanced Enums allow the definition of custom constructors, enabling more dynamic instantiation of enum values.

enum LogLevel {
  debug,
  info,
  warning,
  error,

  // Custom Constructor in the Enhanced Enum
  LogLevel.custom(String customLevel) : this._(customLevel);

  final String _value;

  const LogLevel._(this._value);
}

void main() {
  final customLogLevel = LogLevel.custom("custom");
  print(customLogLevel); // Outputs: "custom"
}

Benefits and Use Cases

  1. Code Organization: Enhanced Enums contribute to more organized and modular code, especially when enum variants encapsulate specific functionalities.

  2. Readability: By treating enums more like classes, the code becomes more self-explanatory and readable. This is particularly beneficial for developers collaborating on a project.

  3. Behavioral Enum Variants: Enums can now have behavior, making them suitable for scenarios where each enum variant needs to perform specific actions.

  4. Data-Driven Enums: The ability to attach properties to enum values allows for more data-driven enum structures, accommodating a broader range of use cases.

More from this blog

Vinit Mepani (Flutter Developer)

270 posts

"Vinit Mepani, passionate coder! Dive into my Dart and Flutter journey on the blog. Let's master these tech wonders together. Happy coding! 🚀"