How to Write Conditional Statements in Dart
Conditional statements in Dart allow you to execute different blocks of code based on certain conditions. Dart supports several types of conditional statements, including if, if-else, else if, and switch. Below, we will explore each type with detailed explanations and sample code.
1. Using if
Statement
The if
statement evaluates a condition and executes a block of code if the condition is true
.
void main() {
int number = 10;
if (number > 0) {
print('$number is positive.');
}
}
2. Using if-else
Statement
The if-else
statement allows you to execute one block of code if the condition is true
and another block if the condition is false
.
void main() {
int number = -5;
if (number > 0) {
print('$number is positive.');
} else {
print('$number is not positive.');
}
}
3. Using else if
Statement
The else if
statement allows you to check multiple conditions sequentially. If the first condition is false
, it checks the next condition, and so on.
void main() {
int number = 0;
if (number > 0) {
print('$number is positive.');
} else if (number < 0) {
print('$number is negative.');
} else {
print('$number is zero.');
}
}
4. Using switch
Statement
The switch
statement is used to execute one block of code among many based on the value of a variable. It is particularly useful when you have multiple conditions to check against a single variable.
void main() {
String day = 'Monday';
switch (day) {
case 'Monday':
print('Start of the week.');
break;
case 'Wednesday':
print('Midweek day.');
break;
case 'Friday':
print('End of the work week.');
break;
default:
print('Just another day.');
}
}
5. Conditional Expressions
Dart also supports conditional expressions, which allow you to write concise conditional logic in a single line. The syntax is condition ? expressionIfTrue : expressionIfFalse
.
void main() {
int number = 5;
String result = (number % 2 == 0) ? 'Even' : 'Odd';
print('$number is $result.');
}
Conclusion
Conditional statements are a fundamental part of programming in Dart, allowing you to control the flow of your application based on specific conditions. By using if
, if-else
, else if
, switch
, and conditional expressions, you can implement complex logic in your Dart applications effectively.