Introduction:
Learn all about Dart switch statements in this comprehensive guide. Dart’s switch statement allows you to handle multiple conditions based on the value of an expression, providing a concise and efficient way to control program flow. Whether you’re a beginner or an experienced Dart developer, understanding switch statements is essential for writing clean and readable code. This guide covers everything you need to know about switch statements in Dart, including syntax, usage, best practices, and real-world examples.
In Dart, the switch statement allows you to conditionally execute different blocks of code based on the value of a variable.
dart
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// Additional cases as needed
default:
// Code to execute if expression doesn’t match any case
}
expression: This is the variable or expression whose value you want to compare against various cases.
case value: This is one of the possible values that expression can take. If expression equals value, the corresponding block of code will be executed.
break: This keyword is used to exit the switch statement after a case has been matched and executed. Without a break, execution will continue to the next case regardless of whether it matches.
default: This is an optional case that will be executed if none of the other cases match the value of expression. It’s similar to the else statement in an if-else construct.
Here’s a simple example to illustrate how a switch statement works:
dart
void main() { String fruit = 'apple'; switch (fruit) { case 'apple': print('Selected fruit is an apple'); break; case 'banana': print('Selected fruit is a banana'); break; case 'orange': print('Selected fruit is an orange'); break; default: print('Selected fruit is unknown'); } }
In this example, if the value of fruit is ‘apple’, it will print ‘Selected fruit is an apple’. If the value is ‘banana’, it will print ‘Selected fruit is a banana’, and so on. If fruit has a value other than ‘apple’, ‘banana’, or ‘orange’, it will print ‘Selected fruit is unknown’ because of the default case.
Here’s a comprehensive example demonstrating various aspects of using the switch statement in Dart:
dart
void main() { String grade = 'B'; switch (grade) { case 'A': case 'B': print('Excellent or Good'); break; case 'C': print('Average'); break; case 'D': case 'E': print('Below Average'); break; case 'F': print('Fail'); break; default: print('Invalid grade'); } // Using switch with integers int number = 5; switch (number) { case 1: print('One'); break; case 2: print('Two'); break; case 3: print('Three'); break; default: print('Unknown number'); } // Using switch with enums var direction = Direction.east; switch (direction) { case Direction.north: print('Heading North'); break; case Direction.south: print('Heading South'); break; case Direction.east: print('Heading East'); break; case Direction.west: print('Heading West'); break; } } enum Direction { north, south, east, west }
Multiple cases: You can stack multiple cases together if they should have the same behavior.
Using integers: switch statements in Dart can also be used with integers.
Using enums: Enums can be used with switch statements, providing a clean and readable way to handle different states or options.
Some of the capabilities and nuances of the Dart switch statement with some additional examples:
In Dart, unlike some other languages, there’s no automatic fall-through behavior in switch statements. However, you can achieve fall-through behavior by omitting the break statement. Here’s an example:
dart
void main() { int number = 2; switch (number) { case 1: print('One'); // No break statement, falls through to the next case case 2: print('Two'); break; case 3: print('Three'); break; default: print('Unknown number'); } }
In this case, if number is 1, it will print both ‘One’ and ‘Two’ because there’s no break statement after the ‘One’ case.
You can use constant expressions (such as const variables or literals) in case labels. This can help catch errors at compile time and improve performance.
dart
void main() { const int option = 2; switch (option) { case 1: print('Option 1'); break; case 2: print('Option 2'); break; default: print('Invalid option'); } }
You can use continue to skip the rest of the code in a particular case and move to the next iteration of the loop containing the switch statement. continue outer can be used to skip to the next iteration of an outer loop.
dart
void main() { for (int i = 0; i < 5; i++) { switch (i) { case 2: print('Skipping 2'); continue; case 3: print('Skipping 3'); continue outer; // Skips to the next iteration of the outer loop default: print('Processing $i'); } } }
Let’s explore a few advanced features and techniques with the Dart switch statement:
You can use switch statements within functions to return a value based on different cases:
dart
String getMessage(int status) { switch (status) { case 200: return 'Success'; case 404: return 'Not Found'; case 500: return 'Internal Server Error'; default: return 'Unknown Status'; } } void main() { print(getMessage(200)); // Output: Success print(getMessage(404)); // Output: Not Found print(getMessage(403)); // Output: Unknown Status }
Dart allows you to switch based on the type of an object. This is particularly useful in situations where you need to perform different operations based on the type of an object:
dart
void process(dynamic value) { switch (value.runtimeType) { case int: print('Integer: $value'); break; case double: print('Double: $value'); break; case String: print('String: $value'); break; default: print('Unknown Type'); } } void main() { process(10); // Output: Integer: 10 process(3.14); // Output: Double: 3.14 process('Hello'); // Output: String: Hello process(true); // Output: Unknown Type }
You can use assertions within switch cases to ensure that certain conditions are met. This can be helpful during development to catch unexpected states:
dart
void main() { int number = 5; switch (number) { case 1: print('One'); break; case 2: print('Two'); break; default: assert(number > 0, 'Number must be greater than 0'); print('Unknown number'); } }
In this example, if number is not 1 or 2, the assert statement ensures that number is greater than 0.
In Dart, you can include conditions in case labels using boolean expressions. This allows for complex matching logic within the switch statement:
dart
void main() { int number = 7; switch (number) { case 1: print('One'); break; case 3: case 5: case 7: print('Odd number'); break; case 2: case 4: case 6: print('Even number'); break; default: print('Unknown number'); } }
In this example, the cases 3, 5, and 7 all lead to the execution of ‘Odd number’, demonstrating how multiple cases can share the same logic.
You can nest switch statements within each other, known as cascading switch statements. This can be useful for organizing complex logic:
dart
void main() { int score = 75; String grade; switch (score ~/ 10) { case 10: case 9: grade = 'A'; break; case 8: grade = 'B'; break; case 7: grade = 'C'; break; case 6: grade = 'D'; break; default: grade = 'F'; } switch (grade) { case 'A': print('Excellent'); break; case 'B': print('Good'); break; case 'C': print('Average'); break; case 'D': print('Below Average'); break; case 'F': print('Fail'); break; default: print('Invalid grade'); } }
You can use switch statements within loops, and use continue and break statements to control the loop flow based on switch cases:
dart
void main() { for (int i = 0; i < 5; i++) { switch (i) { case 2: print('Skipping 2'); continue; case 3: print('Breaking at 3'); break; default: print('Processing $i'); } } }
In this example, when i equals 2, it skips to the next iteration of the loop using continue, and when i equals 3, it breaks out of the loop using break.
Let’s explore some complete examples demonstrating the various uses of the Dart switch statement along with explanations for each example:
dart
void main() { int marks = 85; String grade; switch (marks ~/ 10) { case 10: case 9: grade = 'A'; break; case 8: grade = 'B'; break; case 7: grade = 'C'; break; case 6: grade = 'D'; break; default: grade = 'F'; } print('Grade: $grade'); }
This example calculates the grade based on the marks obtained.
The switch statement divides the marks by 10 using integer division (~/) to get the tens place of the marks.
Based on the tens place, it assigns a grade using different cases.
It then prints out the calculated grade.
dart
void main() { int day = 5; String dayName; switch (day) { case 1: dayName = 'Monday'; break; case 2: dayName = 'Tuesday'; break; case 3: dayName = 'Wednesday'; break; case 4: dayName = 'Thursday'; break; case 5: dayName = 'Friday'; break; case 6: dayName = 'Saturday'; break; case 7: dayName = 'Sunday'; break; default: dayName = 'Invalid day'; } print('Day: $dayName'); }
This example maps a numeric value to the corresponding day of the week.
The switch statement matches the numeric value of the day and assigns the appropriate day name to dayName.
If the numeric value doesn’t match any of the cases, it assigns ‘Invalid day’.
Finally, it prints out the resolved day name.
dart
enum Role { admin, , moderator } void main() { Role role = Role.admin; String roleMessage; switch (role) { case Role.admin: roleMessage = 'You have administrative privileges'; break; case Role.: roleMessage = 'You have regular privileges'; break; case Role.moderator: roleMessage = 'You have moderator privileges'; break; default: roleMessage = 'Unknown role'; } print(roleMessage); }
This example demonstrates the usage of switch with enum types.
It defines an enum called Role with three different roles: admin, , and moderator.
The switch statement matches the value of the role variable against different roles and assigns an appropriate message to roleMessage.
Finally, it prints out the message indicating the ‘s role.
These examples showcase the versatility of the Dart switch statement in different scenarios, from grade calculation to mapping values to meaningful representations.
dart
void main() { String languageCode = 'fr'; String greeting; switch (languageCode) { case 'en': greeting = 'Hello!'; break; case 'fr': greeting = 'Bonjour!'; break; case 'es': greeting = '¡Hola!'; break; default: greeting = 'Language not supported'; } print(greeting); }
This example maps language codes to greetings in different languages.
The switch statement matches the language code and assigns the appropriate greeting to the greeting variable.
If the language code doesn’t match any of the cases, it assigns ‘Language not supported’.
Finally, it prints out the greeting in the specified language.
dart
void main() { int option = 3; switch (option) { case 1: print('Selected option: Add'); break; case 2: print('Selected option: Edit'); break; case 3: print('Selected option: Delete'); break; case 4: print('Selected option: View'); break; default: print('Invalid option'); } }
This example simulates a menu selection scenario.
The switch statement matches the selected option and prints out the corresponding action.
If the selected option doesn’t match any of the cases, it prints ‘Invalid option’.
dart
enum AuthStatus { authenticated, unauthenticated, pending } void main() { AuthStatus status = AuthStatus.authenticated; switch (status) { case AuthStatus.authenticated: print(' is authenticated'); break; case AuthStatus.unauthenticated: print(' is not authenticated'); break; case AuthStatus.pending: print('Authentication status is pending'); break; } }
This example demonstrates the usage of switch with an enum representing authentication status.
The switch statement matches the authentication status and prints out the corresponding message.
It handles different states such as authenticated, unauthenticated, and pending.
These examples illustrate how the Dart switch statement can be utilized in various contexts, from language translation to menu selection and authentication status handling. It provides a concise and readable way to handle multiple cases based on a single expression.
Here’s the code for the application along with explanations:
dart
import 'dart:math'; void main() { print('Shape Area Calculator'); print('---------------------'); print('Select a shape:'); print('1. Circle'); print('2. Rectangle'); print('3. Triangle'); print('4. Exit'); // Read input int choice = int.parse(stdin.readLineSync()!); switch (choice) { case 1: calculateCircleArea(); break; case 2: calculateRectangleArea(); break; case 3: calculateTriangleArea(); break; case 4: print('Exiting the program. Goodbye!'); break; default: print('Invalid choice. Please select a valid option.'); } } void calculateCircleArea() { print('Enter the radius of the circle:'); double radius = double.parse(stdin.readLineSync()!); double area = pi * radius * radius; print('The area of the circle is: $area'); } void calculateRectangleArea() { print('Enter the length of the rectangle:'); double length = double.parse(stdin.readLineSync()!); print('Enter the width of the rectangle:'); double width = double.parse(stdin.readLineSync()!); double area = length * width; print('The area of the rectangle is: $area'); } void calculateTriangleArea() { print('Enter the base length of the triangle:'); double base = double.parse(stdin.readLineSync()!); print('Enter the height of the triangle:'); double height = double.parse(stdin.readLineSync()!); double area = 0.5 * base * height; print('The area of the triangle is: $area'); }
This Dart application allows s to calculate the area of different shapes using a switch statement.
The main() function displays a menu of shape options (circle, rectangle, triangle, and exit) and reads the ‘s choice.
Based on the ‘s choice, it calls different functions to calculate the area of the selected shape.
Each shape calculation function (calculateCircleArea(), calculateRectangleArea(), calculateTriangleArea()) prompts the to enter necessary parameters (e.g., radius, length, width, height) and calculates the area accordingly.
The application utilizes a switch statement to handle different choices and execute the corresponding code block.
If the enters an invalid choice, the default case of the switch statement handles it by printing an error message.
You can run this Dart application to calculate the area of various shapes based on input.
Below is a quiz about Dart switch statements along with explanations for each question and answer:
A) To iterate over a collection
B) To handle multiple conditions based on the value of an expression
C) To define a function
D) To create a loop
Answer: B) To handle multiple conditions based on the value of an expression
Explanation: The Dart switch statement is used to evaluate an expression and execute different blocks of code based on the value of that expression.
A) return
B) exit
C) break
D) continue
Answer: C) break
Explanation: The break keyword is used to exit a case block in a switch statement. It prevents fall-through behavior, where execution continues to the next case.
A) int
B) String
C) enum
D) All of the above
Answer: D) All of the above
Explanation: In Dart, you can use switch statements with various data types including int, String, and enum.
A) To terminate the program
B) To handle the default behavior when none of the other cases match
C) To skip to the next iteration of the loop
D) To execute if the expression matches any case
Answer: B) To handle the default behavior when none of the other cases match
Explanation: The default case in a switch statement is executed when none of the other cases match the value of the expression. It provides a fallback option.
A) Yes, but only if they are consecutive
B) No, each case must have a unique block of code
C) Yes, you can have multiple case labels for the same block of code
D) Yes, but only if they are separated by a comma
Answer: C) Yes, you can have multiple case labels for the same block of code
Explanation: Dart allows multiple case labels to share the same block of code, which can help reduce redundancy and improve readability.
A) The program terminates
B) It results in a compilation error
C) Execution continues to the next case block regardless of whether it matches
D) The default case is automatically executed
Answer: C) Execution continues to the next case block regardless of whether it matches
Explanation: If a break statement is omitted after a case block in a switch statement, execution will continue to the next case block, even if the current block matches the value of the expression.
A) No, case labels must be constant values
B) Yes, you can use expressions or conditions in case labels
C) Only if the expression is of type int
D) Only if the expression is of type String
Answer: A) No, case labels must be constant values
Explanation: In Dart, case labels must be constant values, meaning they cannot be expressions or conditions. This restriction ensures that the switch statement can be efficiently compiled.
A) It terminates the loop
B) It skips the rest of the code in the current case block and proceeds to the next iteration of the loop
C) It jumps to the next case block
D) It returns a value from the function
Answer: B) It skips the rest of the code in the current case block and proceeds to the next iteration of the loop
Explanation: The continue statement in a switch statement is used to skip the remaining code in the current case block and continue with the next iteration of the loop containing the switch statement.
A) When the number of conditions is large and there is a need for fall-through behavior
B) When the conditions involve complex expressions
C) When you need to handle only a few specific cases
D) When the conditions involve boolean logic
Answer: C) When you need to handle only a few specific cases
Explanation: switch statements are typically used when you have multiple specific cases to handle based on the value of an expression. If you only have a few cases to consider, an if-else statement might be appropriate.
A) When you want to execute a specific block of code if none of the other cases match
B) When you want to terminate the program
C) When you want to skip the current iteration of the loop
D) When you want to execute the default behavior regardless of the condition
Answer: A) When you want to execute a specific block of code if none of the other cases match
Explanation: The default case in a switch statement is used to specify the default behavior when none of the other cases match the value of the expression. It provides a fallback option.
A) The program terminates with an error.
B) The switch statement executes the code in the next case block.
C) The switch statement does nothing and continues to the next line of code.
D) It results in a compilation error.
Answer: C) The switch statement does nothing and continues to the next line of code.
Explanation: If the expression in a switch statement does not match any of the case values and there is no default case, the switch statement will do nothing and continue to the next line of code.
A) Yes, but only if the switch statement is nested within a loop.
B) Yes, the ‘continue’ statement can be used in any case block of a switch statement.
C) No, the ‘continue’ statement is not allowed in switch statements.
D) Yes, but only if the switch statement is nested within another switch statement.
Answer: C) No, the ‘continue’ statement is not allowed in switch statements.
Explanation: The ‘continue’ statement is not allowed in switch statements. Instead, you can use ‘break’ to exit the switch statement or ‘continue’ to skip to the next iteration of a loop.
A) Case labels must be in ascending order.
B) Case labels must be in descending order.
C) Case labels can be in any order.
D) Case labels must be in alphabetical order.
Answer: C) Case labels can be in any order.
Explanation: In Dart, case labels can be in any order within a switch statement. There is no requirement for them to be in a specific order.
A) Yes, as long as there is a default case.
B) No, a switch statement must have at least one case label.
C) Yes, but the switch statement will result in a compilation error.
D) Yes, but the switch statement will not execute any code.
Answer: B) No, a switch statement must have at least one case label.
Explanation: A switch statement must have at least one case label to define the different cases to evaluate.
A) It skips to the next case label.
B) It exits the switch statement and continues with the code after the switch statement.
C) It skips to the default case label.
D) It terminates the program.
Answer: B) It exits the switch statement and continues with the code after the switch statement.
Explanation: The ‘break’ statement in a switch statement is used to exit the switch statement and continue with the code after the switch statement. It prevents fall-through behavior, where execution continues to the next case label.
What?s Taking place i am new to this, I stumbled upon this I’ve discovered It absolutely useful and it has helped me out loads. I am hoping to contribute & help different customers like its helped me. Great job.
These days of austerity as well as relative anxiety about taking on debt, many people balk about the idea of making use of a credit card in order to make purchase of merchandise and also pay for a vacation, preferring, instead to rely on a tried in addition to trusted procedure for making settlement – raw cash. However, if you have the cash there to make the purchase 100 , then, paradoxically, this is the best time for you to use the card for several reasons.
Hey there! I know this is kinda off topic but I’d figured I’d ask. Would you be interested in trading links or maybe guest writing a blog post or vice-versa? My blog covers a lot of the same subjects as yours and I believe we could greatly benefit from each other. If you’re interested feel free to send me an e-mail. I look forward to hearing from you! Awesome blog by the way!