Dart Extensions are what I’ve been waiting for

dart-enum-values-via-extensions

Dart doesn’t allow Enums with values, but with extensions that’s now possible.

void main() { 
  Status stat = Status.running;
  print( "what is the status value? " + stat.value.toString() ); // output = 2
}


enum Status { 
   none, 
   running, 
   stopped, 
   paused 
}

extension StatusInt on Status {
  int get value {
    switch( this ) {
      case Status.none: return 0;
      case Status.paused: return 1;
      case Status.running: return 2;
      case Status.stopped: return 3;
      default: return -1;
    }
  }
}

One thought on “Dart Extensions are what I’ve been waiting for

Leave a Reply

Your email address will not be published. Required fields are marked *