DEV Community

Cover image for Dart Control Flow Statement: From If-Else to Loops and More -Part 2
Sadanand gadwal
Sadanand gadwal

Posted on • Updated on

Dart Control Flow Statement: From If-Else to Loops and More -Part 2

Dive into the world of Dart programming, the fundamental control flow structures of Dart 3, including if-else blocks, if-else-if blocks, switch statements, and switch expressions. Learn how to leverage these constructs effectively in your Dart programs for better control and readability.

Dart Control Flow Statement

In Dart, the Control flow statement can be categorized mainly in three ways.

1. Decision-making statements
2. Looping statements
3. Jump statements

Image description

Initialization and Constants:

const temperature = 43;
Enter fullscreen mode Exit fullscreen mode

In this line, a constant named temperature is declared and assigned a value of 43. Constants are variables whose values cannot be changed once assigned. Here, temperature represents the temperature value to be evaluated.

1.1 If Block Structure:
The "if" statement in programming allows you to execute a block of code if a specified condition is true. It provides a basic branching mechanism where the code block associated with the "if" statement is executed only if the condition evaluates to true.

if (temperature < 10) {
    print("Very Cold");
}
Enter fullscreen mode Exit fullscreen mode

In this example, the "if" statement checks if the value of the variable "temperature" is less than 10. If the condition is true (temperature is less than 10), it prints "Very Cold" to the console. If the condition is false, the code block associated with the "if" statement is simply skipped, and no further action is taken.

1.1 If-Else Block Structure:
The if-else statement in Dart allows you to execute a block of code if a condition is true, and another block if the condition is false. It provides a basic branching mechanism in programming logic.

if (temperature < 10){
  print("Very Cold");
} else {
  print("Not very cold");
}
Enter fullscreen mode Exit fullscreen mode

This section employs an if-else block to check whether the temperature is less than 10. If the condition is true, the code prints "Very Cold"; otherwise, it prints "Not very cold". This simple if-else structure provides a straightforward way to handle binary conditions.

1.3 If-Else-If Block Structure:
The if-else-if statement extends the if-else statement by allowing you to test multiple conditions sequentially. It provides a way to evaluate complex branching logic where there are multiple possible outcomes.

if (temperature < 10) {
  print("Very Cold");
} else if (temperature >= 10 && temperature <= 18) {
  print("Cold");
} else if (temperature >= 10 && temperature <= 24) {
  print("Normal");
} else if (temperature >= 10 && temperature <= 35) {
  print("Hot");
} else if (temperature >= 10 && temperature <= 40) {
  print("Very Hot");
} else {
  print("Really too Hot");
}
Enter fullscreen mode Exit fullscreen mode

This section presents a series of if-else-if blocks to evaluate the temperature against specific ranges and determine the appropriate weather conditions. Each condition is mutually exclusive, ensuring that only one condition is met.

1.4 Switch Statement:
The switch statement in Dart provides an alternative way to express multi-branching logic. It evaluates an expression against a list of possible cases and executes the code block associated with the first matching case. It's particularly useful when dealing with multiple possible values for a variable.

switch (temperature) {
  case < 10:
    print("Very Cold");
    break;
  case > 10 && <= 18:
    print("Cold");
    break;
  case > 10 && <= 24:
    print("Normal");
    break;
  case > 10 && <= 34:
    print("Hot");
    break;
  case > 10 && <= 40:
    print("Very Cold");
    break;
  default:
    print("Really Too Hot");
    break;
}
Enter fullscreen mode Exit fullscreen mode

Here, a switch statement is used to evaluate the temperature and print the corresponding weather condition based on different temperature ranges defined in the cases. However, the use of inequalities within the case labels is not syntactically correct in Dart. This code won't work as intended.

1.5 Switch Expression in Dart 3:
Introduced in Dart 2.3, the switch expression is a concise way to express multi-branching logic. It evaluates an expression against a list of cases, similar to the switch statement, but it returns a value based on the matched case instead of executing code blocks. This enhances readability and conciseness, especially in functional programming contexts.

final status = switch(temperature){
  <10 => "very cold",
  >= 10 && <= 18 => "Cold",
  >= 10 && <= 24 => "Normal",
  >= 10 && <= 34 => "Hot",
  >= 10 && <= 40 => "Very Cold",
  _ => "Really Too Hot",
};
print(status);
Enter fullscreen mode Exit fullscreen mode

This section showcases the switch expression introduced in Dart 3. It allows for concise pattern matching and assignment of values based on conditions. However, the use of inequalities within the switch expression is also not valid in Dart and will not work as intended.

2.1 While Loop:
A while loop is a control flow statement that executes a block of code repeatedly as long as a specified condition evaluates to true. The condition is evaluated before each iteration. If the condition is false initially, the block of code inside the loop is never executed.

int index = 1;
while (index < marks.length) {
    print(marks[index]);
    index++;
}
Enter fullscreen mode Exit fullscreen mode

The while loop continues to execute as long as the condition index < marks. length evaluates to true. It prints the element at the current index of the marks list and increments the index by one in each iteration.

**2.2 Do-While Loop:
**A do-while loop is similar to a while loop, but the condition is evaluated after the block of code inside the loop is executed. This means that the block of code is executed at least once, regardless of whether the condition is true or false initially.

do {
    print(marks[index]);
    index++;
} while (index < marks.length);
Enter fullscreen mode Exit fullscreen mode

2.3 For Loop:
A for loop is a control flow statement that iterates over a range of values. It typically includes an initialization step, a condition for continuing the loop, and an iteration step. The loop iterates until the condition becomes false.

for (int i = 0; i < marks.length; i++) {
    print(marks[i]);
}
Enter fullscreen mode Exit fullscreen mode

The for loop is used to iterate over the elements of the marks list. It initializes the loop control variable i to 0 and continues to execute as long as i is less than the length of the marks list. In each iteration, it prints the element at the index i of the list and increments i by one.

3. Break and Continue
break is used to immediately exit the loop when a specific condition is met.
continue is used to skip the remaining code in the current iteration of the loop and proceed to the next iteration.

// While Loop with break and continue
int index = 0;
while (index < marks.length) {
    if (marks[index] == 87) {
        // Use 'continue' to skip printing if the element is 87
        index++;
        continue;
    }
    if (marks[index] == 105) {
        // Use 'break' to exit the loop if the element is 105
        break;
    }
    print(marks[index]);
    index++;
}

// Do-While Loop with break and continue
index = 0;
do {
    if (marks[index] == 87) {
        // Use 'continue' to skip printing if the element is 87
        index++;
        continue;
    }
    if (marks[index] == 105) {
        // Use 'break' to exit the loop if the element is 105
        break;
    }
    print(marks[index]);
    index++;
} while (index < marks.length);

// For Loop with break and continue
print("Printing marks list using for loop");
for (int i = 0; i < marks.length; i++) {
    if (marks[i] == 87) {
        // Use 'continue' to skip printing if the element is 87
        continue;
    }
    if (marks[i] == 105) {
        // Use 'break' to exit the loop if the element is 105
        break;
    }
    print(marks[i]);
}

Enter fullscreen mode Exit fullscreen mode

While Loop:
A while the loop is initialized with a condition. It iterates through the elements of the marks list and prints each element until the loop condition is no longer satisfied. It employs break and continue statements to control the loop flow based on specific conditions.

Do-While Loop:
Similar to the while loop, the do-while loop executes its block of code at least once before evaluating the loop condition. It iterates through the elements of the marks list, employing break and continue statements to control the loop flow based on specific conditions.

For Loop:
The for loop iterates over the elements of the marks list using an index variable. It prints each element until the loop condition is no longer satisfied. It also utilizes break and continue statements to control the loop flow based on specific conditions.

Conclusion:
Understanding Dart's control flow structures like if-else, switch, and loops is crucial for effective programming. With break and continue statements, developers gain finer control over loop execution, enhancing code readability and maintainability. Embrace these techniques to write cleaner, more organized Dart code and unlock the full potential of Dart 3 programming.

🌟 Stay Connected! 🌟

Hey there, awesome reader! 👋 Want to stay updated with my latest insights,Follow me on social media!

🐦 📸 📘 💻 🌐 💼

Sadanand Gadwal

Top comments (0)