Missing case clause error in dart switch case with enums
It's so that you are forced to explicitly handle all use cases, which will lead to fewer bugs. You will either need to add a default
which is the equivalent of 'when null or any unexpected enum value', or explicitly list all remaining enum values.
The best example is when you add a new value to an existing enum, several months after creating that enum, and then you cannot compile the app until you add that new value to all switch cases of that type (unless they were using default
in which case they are already handled).
Neeraj
Updated on December 18, 2022Comments
-
Neeraj over 1 year
I wrote this simple switch case for an enum:
enum Operation { CREATE, UPDATE, DELETE, READ }
...
void check(Operation op) { switch(op) { // dart complains here case Operation.CREATE: insert(); break; case Operation.UPDATE: update(); break; case Operation.DELETE: delete(); break; }
which complains with this error at the
switch(op)
line:error: Missing case clause for 'READ'.
Try adding a case clause for the missing constant, or adding a default constant.It gets fixed if I follow the suggestion and add the
READ
case or adefault
case.
But my question is : why is this so ? Why can't I leave out a case? What if I don't want to check that case here? I checked the dart language docs which says :You can use enums in switch statements, and you’ll get a warning if you don’t handle all of the enum’s values
But in my case, its definitely an error and not a warning. I'm using dart for developing a flutter application (if that makes a difference).