DEV Community

Flutter Tanzania
Flutter Tanzania

Posted on

Control flow in Dart - Part 2

Part 2: Control Flow and Loops

The If Statement

In programming, decisions are crucial. The if statement lets us control the flow of our program based on conditions. Consider this example:

int temperature = 25;

if (temperature > 30) {
  print('It\'s a hot day!');
} else {
  print('It\'s not too hot.');
}
Enter fullscreen mode Exit fullscreen mode

Here, if the temperature is greater than 30, it prints 'It's a hot day!'; otherwise, it prints 'It's not too hot.' This helps our program adapt to different situations.

Else-if Chains

For more complex conditions, we use else if:

int hour = 15;

if (hour < 12) {
  print('Good morning!');
} else if (hour < 18) {
  print('Good afternoon!');
} else {
  print('Good evening!');
}
Enter fullscreen mode Exit fullscreen mode

This checks the time of day and greets accordingly, offering more nuanced decision-making.

Ternary Operator

The ternary operator streamlines simple if-else statements:

int age = 20;
String message = (age >= 18) ? 'You can vote' : 'You cannot vote yet';
print(message);
Enter fullscreen mode Exit fullscreen mode

If age is 18 or above, it says 'You can vote'; otherwise, it says 'You cannot vote yet'. This enhances code readability, especially for concise conditions.

Switch Statements

Switch statements are beneficial for multiple cases:

String grade = 'B';

switch (grade) {
  case 'A':
    print('Excellent!');
    break;
  case 'B':
    print('Good job!');
    break;
  default:
    print('Keep trying!');
}
Enter fullscreen mode Exit fullscreen mode

It provides different feedback based on the grade, offering a clearer alternative to long if-else chains.

Loops

Loops help us automate repetitive tasks. Dart offers various types.

While Loop

while loops repeat while a condition is true:

int count = 0;

while (count < 3) {
  print('Count: $count');
  count++;
}
Enter fullscreen mode Exit fullscreen mode

It prints 'Count: 0', 'Count: 1', and 'Count: 2', showcasing the iterative nature of programming.

For Loop

for loops are handy for a fixed number of iterations:

for (int i = 0; i < 4; i++) {
  print('Iteration: $i');
}
Enter fullscreen mode Exit fullscreen mode

It prints 'Iteration: 0', 'Iteration: 1', 'Iteration: 2', and 'Iteration: 3'. This loop structure is efficient when you know the number of iterations in advance.

Break Statement

To exit a loop prematurely, use break:

int target = 2;

for (int i = 0; i < 5; i++) {
  if (i == target) {
    print('Target reached!');
    break;
  }
  print('Current value: $i');
}
Enter fullscreen mode Exit fullscreen mode

This stops the loop when the target value is reached, adding a layer of control to the iteration process.

Mastering these concepts empowers you to build flexible and dynamic programs, adapting to various scenarios and user inputs. Happy coding!

Top comments (0)