Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
switch-sase Statement | Conditional Statements
Introduction to Dart
course content

Conteúdo do Curso

Introduction to Dart

Introduction to Dart

1. First Acquaintance with Dart
2. Variables and Data Types
3. Conditional Statements
4. List and String
5. Loops

bookswitch-sase Statement

switch-sase Statement

When we have many conditions to check, using multiple if-else statements may not be convenient.

Example

dart

main

copy
12345678910111213141516
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:

dart

main

copy
12345678
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.

dart

main

copy
1234567891011121314151617
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 is dayOfWeek. The switch 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 for dayOfWeek is "Friday". If the value of dayOfWeek does not match any of the cases, the default code block is executed. In this case, the default code block is "Weekend".
What is default?

What is default?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 4
some-alt