Hasen
Hasen

Reputation: 12304

Dart switch statement - Case expressions must be constant

I looked at a few questions regarding this for other languages and some suggest using final but that doesn't seem to work with Dart.

I'm passing in arguments so surely the switch statement cannot contain constants only? A switch statement, much like an if statement is asking if it is or not..ie it's unknown so I don't see how a switch statement can be useful if they have to be constants...?

  setCategory(arga, argb) {
    int result;
    switch (true) {
      case (arga >= 0 && arga < 3 && argb < 35):
        result = 16;
        break;
      case (arga >= 0 && arga < 3 && argb >= 35):
        result = 15;
        break;
        etc

It's returning the error Case expressions must be constant regarding the values arga and argb in the case expressions. What's the best way to remedy this or do I have to use an if statement?

Upvotes: 25

Views: 29562

Answers (4)

onur k
onur k

Reputation: 53

for(int x=0; x<1; x++){
if(ing5<8 && toWhatDegreeRand<=10 && toWhatDegreeRand>7){
  toWhatDegreeRand=9;
}
if(ing4<8 && toWhatDegreeRand<=7 && toWhatDegreeRand>5){
  toWhatDegreeRand=6;
}
if(ing3<8 && toWhatDegreeRand<=5 && toWhatDegreeRand>3){
  toWhatDegreeRand=4;
}//....

}

It can be a little useful.

Upvotes: 2

lrn
lrn

Reputation: 71613

The switch case expressions must be constants for sure.

You have to use if/then chains to do multiple tests based on non-constant values.

You cannot use arguments from the surrounding function in a switch case. What you are trying to do here is not supported by the Dart switch statement.

The Dart switch statement is deliberately kept very simple, so that a compiler can know all the possible cases at compile-time. That's why they must be compile-time constants.

Switch statements are still useful for some kinds of switching, like on enums:

enum Nonse { foo, bar, baz; }

String fooText(Nonse non) {
  switch (non) {
    case Nonse.foo: return "foo";
    case Nonse.bar: return "bar";
    case Nonse.baz: return "baz";
  }
  throw ArgumentError.notNull("non");
}

You can also switch over constant string values or integer values.

Upvotes: 20

Harsh Patel
Harsh Patel

Reputation: 1086

Switch statement requires a constant -> it means already initialized variable with final value

switch (expression) {
  case ONE : {
      statement(s);
  }
  break;
  case TWO: {
      statement(s);
  }
  break;
  default : {
      statement(s);
  }
}

Upvotes: 2

Saeiddjawadi
Saeiddjawadi

Reputation: 332

There are some rules for Switch Case

The default case is optional.

All case expression must be unique.

The case statements can include only constants. It cannot be a variable or an expression.

The data type of the variable and the case expression must match.

There can be any number of case statements within a switch.

you should use 'If Else' statement

Upvotes: 7

Related Questions