Conteúdo do Curso
Introduction to Dart
Introduction to Dart
switch-sase Statement
switch-sase Statement
When we have many conditions to check, using multiple if-else statements may not be convenient.
Example
main
void main() { String dayOfWeek = "Friday"; if (dayOfWeek == "Monday") { print("Today is Monday."); } else if (dayOfWeek == "Tuesday") { print("Today is Tuesday."); } else if (dayOfWeek == "Wednesday") { print("Today is Wednesday."); } else if (dayOfWeek == "Thursday") { print("Today is Thursday."); } else if (dayOfWeek == "Friday") { print("Today is Friday."); } else { print("Weekend"); } }
The code looks confusing, but we can make it more readable.
For such cases, we can use the switch-case
statement.
Switch-case Statement
The switch-case
statement consists of several parts:
main
switch(expresion) { case value_1: //code to be executed case value_2: //code to be executed ............. default: //code to be executed if all cases are not matched }
A switch-case
statement is a construct that allows you to execute a block of code based on the value of a variable. The variable is called the switch variable. The switch variable is evaluated once, and the corresponding block of code is executed.
main
void main() { String dayOfWeek = "Friday"; switch (dayOfWeek) { case "Monday": print("Today is Monday."); case "Tuesday": print("Today is Tuesday."); case "Wednesday": print("Today is Wednesday."); case "Thursday": print("Today is Thursday."); case "Friday": print("Today is Friday."); default: print("Weekend"); } }
- In this example, the
switch
variable isdayOfWeek
. Theswitch
variable is evaluated once, and the corresponding code block is executed; - If one of the conditions is met, then after executing its code block, the subsequent conditions will not be checked, and the code blocks of those conditions will not be executed either;
- In this
case
, the code block fordayOfWeek
is"Friday"
. If the value ofdayOfWeek
does not match any of the cases, thedefault
code block is executed. In thiscase
, the default code block is"Weekend"
.
Obrigado pelo seu feedback!