Dart switch case Statement
Dart switch case Statement
The Dart switch case Statement evaluates an expression and executes different code blocks based on its value. This statement avoids nested multiple if-else statements. It is a simplified form of nested if-else statements.
switch case Statement
The general syntax of the Dart switch case Statement is as follows:
switch(expression)
{
case value1 :{
// code block 1
}
break;
case value2: {
// code block 2
}
break;
// more case options …
case valueN: {
// code block N
}
break;
default: {
// default code statement(s);
}
}
Once the switch expression is evaluated, the expression value is compared with all cases which we have defined inside the switch case.
The value of the variable compares with the multiple cases defined, and if a match is found, then it executes a block of statements associated with that particular case. The assigned value is compared with each case until the match is found. Once the match is found, it identifies the block of code to be executed.
break statement: After executing the code block for a matching case, the break statement is used to exit the switch statement. Without the break statement, the execution will continue to the next case block.
The default case is optional and is used when the expression doesn’t match any of the specified cases. It serves as a catch-all for unmatched values.
Example
Let’s understand the concept with an example.
/* Dart switch-case statement demo Dart Tutorials - www.TestingDocs.com */ void main() { String TShirt_size = "L"; switch (TShirt_size) { case "XL" : { print("TShirt Size -> Extra Large"); } break; case "L" : { print("TShirt Size -> Large"); } break; case "M" : { print("TShirt Size -> Medium"); } break; case "S" : { print("TShirt Size -> Small"); } break; default: { print("Not Valid T Shirt Size!"); } } }
—
Dart Tutorials
Dart tutorial on this website can be found at:
https://www.testingdocs.com/dart-tutorials-for-beginners/
More information on Dart: