Statements in Dart

What are statements?

Statement is kind of declaration to specify the order of execution.

If statement

The if statement is to control execution of single block of code, based on condition.

Use if statement when you have a single condition that controls the execution of a single block of code.

Note: Conditions must use boolean values.

Execution of an if statement:

If condition c1 is true, then the block statement s1 is executed

var c1 = true; // Condition

  var s1 = 'statement 1';

  if (c1) {
    print('Execute $s1');
  }

Else statement

The else statement is to control execution of one of two block of code, based on condition.

The else statements execute only when if condition evaluates to false.

Execution of an If-Else statement:

If condition c1 is true, then the block statement s1 is executed, otherwise the block statement s2 is executed.

var c1 = true; // Condition

  var s1 = 'statement 1';

  var s2 = 'statement 2';

  if (c1) {
    print('Execute $s1');
  } else {
    print('Execute $s2');
  }

For loop statement

A for loop enables you to execute code repeatedly a set number of times. To achieve this, you define a counter variable for the loop, the value of which is changed for each iteration. When the counter variable reaches a limit value that you define, the loop terminates.

The for statement supports iteration.

How for loop works:

  1. Each iteration has its own distinct counter variable.
  2. The first iteration uses the counter variable created by the initial declaration i.e var i =0 in the given example.
  3. The expression created at the end of each iteration uses a fresh variable var i = i+1 bound to the value of current variable and the modifies variable as required for the next iteration.
  4. When the counter variable reaches a limit value that you define, the loop terminates

The following code snippet shows how to use for loop.

main() {
  for (var i = 0; i < 5; i++) {
    print(i);
  }
}

While loop statement

The while-loop is to evaluate a condition prior to loop.

While loops can be very useful if you do not know in advance whether you must perform iterative processing on a variable.

The while statement supports conditional iteration.

A while loop enables you to execute a block of code zero or more times. While loops do not use a counter variable, although you can implement a counter variable by defining it outside the loop and manipulating it for each iteration.

Execution of a while statement:

  1. At the start of each iteration of a while loop, a Boolean condition is checked.
  2. If this condition evaluates to true, an iteration begins.
  3. If the condition evaluates to false, the loop terminates.

If condition c1 becomes false, then execution of the while statement completes normally

var c1 = 21;

  var s1 = 'statement 1';

  while (c1 > 21) {
    print('Execute $s1');
  }

Do loop statement

The do-loop is to evaluate a condition after the loop.

Do loops are very useful when you do not know in advance how many times your code needs to execute. For example, you can use a do loop to prompt a user repeatedly until the user provides valid input.

The do statement supports conditional iteration, where the condition is evaluated after the loop.

Execution of a do statement:

The statement s1 is executed. If that execution continues with no label, or to a label that prefixes the do statement, then the execution of s1 is treated as if it had completed normally.

main() {
  var c1 = false;

  var s1 = 'Statement 1';

  do {
    print('Execute $s1');
  } while (c1);
}

The following code snippet shows how to use do loop

var ageLimit = 20;
  do {
    if (ageLimit == 21) {
      print('Enjoy Hot drinks');
    } else {
      print('Enjoy cool drinks');
    }

    ageLimit++;
  } while (ageLimit <= 21);

Break statement

The break statement is to break to stop looping.

The break statement enables you to exit the loop entirely, and skip to the next line of code outside the loop.

The break statement is particularly useful if you are iterating through an array looking for a record, and you want to exit the loop when you have found the record.

The following code snippet breaks the loop when x is equal to 5.

main() {
  var x = 5;
  while (x == 5) {
    print('Use break to stop looping');
    break;
  }
}

Continue statement

The continue statement is to skip the next loop iteration.

The following code snippet continue iteration until satisfy the expression (i < 4) and the statements between continue and the end of the for body are skipped.

main() {
  for (int i = 1; i <= 5; i++) {
    if (i < 4) {
      continue;
    }
    print(i);
  }
}

Switch statement

The switch statement is to perform an action based on the possible values of a single variable.

The switch statement enables you to execute one of several blocks of code depending on the value of a variable or expression.

  1. Switch statements in Dart compare integer, string, or compile-time constants using ==.
  2. Each non-empty case clause ends with a break statement, as a rule.
  3. Use a default clause to execute code when no case clause matches:

The following code snippet shows how to use switch statement.

main() {
  var browser = 'chrome';
  switch (browser) {
    case 'firefox':
      print('Open firefox browser');
      break;
    case 'chrome':
      print('Open chrome browser');
      break;
    default:
      print('Open internet explorer');
  }
}

Assert statement

The assert statement is to disrupt normal execution if a given boolean condition false.

Execution of an assert statement:

When assertions are not enabled, execution of an assertion immediately completes normally

Enable assertions through a command-line flag: --enable-asserts

When assertions are enabled, execution of an assertion assert(condition, optionalMessage) proceeds as follows:

  1. The first argument to assert can be any expression that resolves to a boolean value.
  2. If the expression’s value is true, the assertion succeeds and execution of the assert statement completes normally.
  3. If it’s false, the assert statement fails and throws an exception an AssertionError.

Example: assertion(condition);

main() {
  // 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'));
}

Example: assertion(condition, optionalMessage);

assert(urlString.startsWith('https'),
      'URL ($urlString) should start with "https".');

In production code, assertions are ignored, and the arguments to assert aren’t evaluated.

For-in statement

The for..in statement is to iterate over Iterables.

The following code shows how to iterate over all of the object's of list.

main() {
  var items = {'Item1', 'Item2', 'Item3'};
  for (var item in items) {
    print(item);
  }
}

/*
Output:
Item1
Item2
Item3
*/

Return statement

The return statement returns a result to the caller of a synchronous function.

The following code snippet shows how to use return statement.

String appendFirstLastItems(List<String> items) {
  if (items.isEmpty) {
    return '';
  }
  return '${items.first} ${items.last}';
}

main() {
  var result = appendFirstLastItems([]);
  print(result);
}

Label statement

A label is an identifier followed by a colon.

A labeled case clause is a case clause within a switch statement.

The following code snippet shows how to use labeled case clause in switch statement.

main() {
  var browser = 'chrome';
  switch (browser) {
    case 'firefox':
      print('Open firefox browser');
      break;
    case 'chrome':
      print('Open chrome browser');
      break;
    default:
      print('Open internet explorer');
  }
}