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?
1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed. 2) All the statements following a matching case execute until a break statement is reached.
Rules for switch statement in C language 1) The switch expression must be of an integer or character type. 2) The case value must be an integer or character constant. 3) The case value can be used only inside the switch statement. 4) The break statement in switch case is not must.
Dart Switch case statement is used to avoid the long chain of the if-else statement. It is the simplified form of nested if-else statement. The value of the variable compares with the multiple cases, and if a match is found, then it executes a block of statement associated with that particular case.
In a switch statement, we pass a variable holding a value in the statement. If the condition is matching to the value, the code under the condition is executed. The condition is represented by a keyword case, followed by the value which can be a character or an integer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With