You can control the flow of your Dart code using any of the following:
if
and else
for
loopsforEach
methodfor-in
statementwhile
and do-while
loopsbreak
and continue
switch
and case
assert
Dart supports if
statements with optional else
statements, as the next sample shows.
// if Statement if(condition){ // Statements } // if-else Statement if(condition){ // Statements }else{ // Statements } // if-else Ladder if(condition1){ // Statements }else if(condition2){ // Statements }else if(condition3){ // Statements ... } ... ... ... else{ // Statements }
Here is the following example:
if (isRaining()) { you.bringRainCoat(); } else if (isSnowing()) { you.wearJacket(); } else { car.putTopDown(); }
Unlike JavaScript, conditions must use boolean values, nothing else.
You can iterate with the standard for loop. For example:
var message = StringBuffer('Dart is fun'); for (var i = 0; i < 5; i++) { message.write('!'); }
If the object that you are iterating over is an Iterable, you can use the forEach()
method. Using forEach()
is a good option if you don’t need to know the current iteration counter:
candidates.forEach((candidate) => candidate.interview()); // or, candidates.forEach(function(candidate){ return candidate.interview(); });
Iterable classes such as List and Set also support the for-in
form of iteration:
var collection = [0, 1, 2]; for (var x in collection) { print(x); // 0 1 2 }
A while
loop evaluates the condition before the loop:
while(condition){ // Statements }
For example,
while (!isDone()) { doSomething(); }
The condition is tested first. If the condition is evaluated as true
, then the statement of while body executed otherwise the control goes out of the while loop.
A do-while loop evaluates the condition after the loop:
do{ // Statements }while(condition);
The statements in the do
body is executed first, then the condition is checked. If the condition becomes true
, the statements get executed for the second time. That means even if in the first attempt, the condition becomes false
, there's a gaurentee that the statements will be executed for at least once.
do { printLine(); } while (!atEndOfPage());
Use break
statement to terminate the loop and let the control goes out of it.
while (true) { if (shutDownRequested()) break; processIncomingRequests(); }
When the control goes to break
statement, the loop breaks. Generally the break
statement appears inside a if
statement.
Use continue
to skip to the next loop iteration:
for (int i = 0; i < candidates.length; i++) { var candidate = candidates[i]; if (candidate.yearsExperience < 5) { continue; } candidate.interview(); }
Whenever the control meets the continue
statement, the following statements after it gets skipped and starts a new iteration. Generally continue
statement is appeared within the if
statement.
switch(value){ case value1: statements1 break; case value2: statements2 break; ... default: statements }
The value should be integer
, string
, or compile time constants.
When the control gets inside the switch
statement, the value of first case
statement is checked against the value in the switch
statement, if it matches, then the corresponding statements under that case
statement gets executed. If the value doesn't match, then the next case
statement gets checked. This way it goes to the last case
statement until a match is found. If no match s found against any case
statement, then the default
statements gets executed if there is any.
To terminate the execution of the case
statement, use break
statement.
As a rule, if there is any statement present under the case
statement, the break
statement must be present to terminate the switch
statement. Otherwise, there will be an error.
The following example omits the break
statement in a case
clause, thus generating an error:
var command = 'OPEN'; switch (command) { case 'OPEN': executeOpen(); // ERROR: Missing break case 'CLOSED': executeClosed(); break; }
However, Dart does support empty case
clauses, allowing a form of fall-through:
var command = 'CLOSED'; switch (command) { case 'CLOSED': // Empty case falls through. case 'NOW_CLOSED': // Runs for both CLOSED and NOW_CLOSED. executeNowClosed(); break; }
Here is an example of switch-case statement
var command = 'OPEN'; switch (command) { case 'CLOSED': executeClosed(); break; case 'PENDING': executePending(); break; case 'APPROVED': executeApproved(); break; case 'DENIED': executeDenied(); break; case 'OPEN': executeOpen(); break; default: executeUnknown(); }
If you want both, statements as well as fall-through mechanism, then you can use continue
statement to achieve this goal:
var command = 'CLOSED'; switch (command) { case 'CLOSED': executeClosed(); continue nowClosed; // Continues executing at the nowClosed label. nowClosed: case 'NOW_CLOSED': // Runs for both CLOSED and NOW_CLOSED. executeNowClosed(); break; }
During development, use an assert statement to disrupt normal execution if a boolean condition is false
. Here are some more:
assert(condition, optionalMessage);
// Make sure the variable has a non-null value. assert(text != null); // Make sure the value is less than 100. assert(number < 100); // Make sure this is an https URL. assert(urlString.startsWith('https'));
To attach a message to an assertion, add a string as the second argument to assert
.
assert(urlString.startsWith('https'), 'URL ($urlString) should start with "https".');
The first argument of assert
is a condition. But you can use a expression or a function call that returns a boolean value.