Enums

Enums

About

  • Enums define fixed sets of values.
  • Lightweight alternative to classes.
  • Support methods and properties.
  • Enable exhaustive switching.

Main Topics

  1. Basic Enum

    • Definition: enum keyword.
    • Example:
      enum Status { pending, approved, rejected }
  2. Enhanced Enums

    • **Definition`: Members and methods.

    • Example:

      enum Status {
        pending('Pending'),
        approved('Approved');
      
        final String label;
        const Status(this.label);
      }
  3. Pattern Matching

    • **Definition`: Exhaustive switches.
    • Example:
      String describe(Status s) => switch(s) {
        Status.pending => 'Waiting',
        Status.approved => 'Confirmed'
      };
  4. State Representation

    • **Definition`: Finite state machines.
    • Example:
      enum AuthState { loggedOut, loggedIn }

How to Use

  • Declare: Simple value lists
  • **Enhance`: Add properties/methods
  • **Switch`: Exhaustive pattern matching
  • **Convert: name` property for strings

How It Works

  • **Values`: Fixed at compile-time
  • **Safety`: Compiler knows all cases
  • **Performance`: More efficient than strings

Example Session:

void main() {
  var status = Status.pending;
  print(status.label); // Enhanced enum property
}

Conclusion

Dart enums evolve beyond simple value sets into powerful state modeling tools through enhanced capabilities and pattern matching support.