Dart: Control Flow

 

Control Flow

Control flow lets you dictate that certain lines of code are executed, skipped over, or repeated. Control flow is handled in Dart with conditionals and loops.

Decision Making
  • Conditionals

The most basic form of control flow is deciding whether to execute or skip over certain parts of your code, depending on conditions that occur as your program runs. The language construct for handling conditions is the if/else statement. if/else in Dart looks nearly identical to the use in other C-like languages.

Suppose you have an animal variable that's currently a fox.

  • While Loops

Loops let you repeat code a certain number of times or based on certain conditions. The latter are handled by while loops.

There are two forms of while loop in Dart, while and do-while. The difference is that for while, the loop condition is before the code block, and in do-while the condition is after. So for do-while, the code block is guaranteed to run at least one time.

Create a variable i initialized to 1:

var i = 1
  • continue and break

Dart has the usual continue and break keywords for use in loops and elsewhere. continue will skip remaining code inside a loop and immediately go to the next iteration. break stops the loop and continues execution after the body of the loop.

You must be careful when using continue in your code. For example, if you take the do-while loop from above, and say you want to continue when i is equal to 5, that could result in an infinite loop that just keeps running, depending in where you place the continue statement:

do { print(i); if (i == 5) { continue; } ++i; } while (i < 10);

 

  • For Loops

The loops that loop a pre-determined number of times are for loops in Dart, which once again are very similar to those from other languages.

For the for-in form, a variable is set to each element in a collection of Dart objects for each subsequent iteration of the loop. Let's say you want to sum up the values of the first 10 integers.

Create a variable for the sum:

var sum = 0;

Then use a for loop in which you initialize a loop counter i to 1, check that i is less than or equal to 10, and increment i after every loop. Inside the loop use a compound assignment to add i to the running sum:

for (var i = 1; i <= 10; i++) {
  sum += i;  
}
print("The sum is $sum"); 
  • switch and enum

Dart also has support for a switch statement and enumerations using enum. Consult the Dart documentation for more on both. Like most of the rest of the Dart constructs you've seen, they work similarly to how they work in other languages like C and Java.

Comments

Popular posts from this blog

Flutter : Introduction

How to release your Flutter app

Firebase Cloud Messaging