skip to Main Content

I am having this enum:

enum ContentError {
  e410('Exception: 410'),
  e411('Excetion: 411'),
  e412('Exception: 412'),
  e413('Exception: 413');

  const ContentError(this.name);

  final String name;
}

Now I get some String and I want to do a switch case on the names of the Enum.

switch (myString) {
  case ContentError.e410.name:
    // do something
  ...
}

but this does not work as it says The property 'name' can't be accessed on the type 'ContentError' in a constant expression.

How can I do a switch case on the Enum attriute name?

2

Answers


  1. Try this!

    enum ContentError {
      e410,
      e411,
      e412,
      e413,
    }
    
    extension ContentErrorExtension on ContentError {
      String get name {
        switch (this) {
          case ContentError.e410:
            return 'Exception: 410';
          case ContentError.e411:
            return 'Exception: 411';
          case ContentError.e412:
            return 'Exception: 412';
          case ContentError.e413:
            return 'Exception: 413';
          default:
            return '';
        }
      }
    }
    
    void main() {
      String myString = 'Exception: 410';
    
      switch (myString) {
        case ContentError.e410.name:
          print('Handling Exception 410');
          break;
        case ContentError.e411.name:
          print('Handling Exception 411');
          break;
        case ContentError.e412.name:
          print('Handling Exception 412');
          break;
        case ContentError.e413.name:
          print('Handling Exception 413');
          break;
        default:
          print('Unhandled exception');
      }
    }
    
    Login or Signup to reply.
  2. You can change the switch case and define the action each case using map and returning the method to execute correct conditions, the step explained in the code below:

    // your input
    final myString = ContentError.e410.name;
    
    // define the action rule, like switch case
    final rule = {
      ContentError.e410.name: () {
        print('do something e410');
      },
      ContentError.e411.name: () {
        print('do something e411');
      },
      ContentError.e412.name: () {
        print('do something e412');
      },
      ContentError.e413.name: () {
        print('do something e413');
      },
    }[myString];
    
    // default action, act like default 
    // in the switch case
    final def = () {
      print('default');
    };
    
    // execute the rule result
    // if rule not contains the input
    // then call default action
    (rule ?? def)();
    

    And this is the results:

    enter image description here

    enter image description here

    enter image description here

    enter image description here

    Hopefully it can solve your problem, Thanks 😉

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search