While loop allows you to execute statements based on conditional value. Dart language provides the following two kinds of while loops.

  • Dart While Loop
  • Dart Do While Loop

Dart While Loop example

It executes the code statement multiple times based on the bool value.

Here is the syntax of a while loop.

while(conditional expression){
  //statements
}

while is a keyword in a dart that can not be used as a variable name in a dart.

conditional-expression is a dart expression evaluated to true or false only. if it is true, Statements inside a while loop are executed.

the conditional expression must enclose in (()).

code block contains a single line or block(multiple lines) of code. Multiple lines of code must be enclosed in {}, and it is optional for single lines of code. It is not recommended to write without {}.

Here are while loop examples in dart

void main() {
  var number = 10;
  var sum = 0;

  while (number >= 1) {
    sum = sum + number;
    number--;
  }
  print("The Sum is ${sum}");
}

Output:

The Sum is 55

Dart Do While Loop example

Do While is to execute multiple blocks of code based on conditional expression value.

Do While Loop is similar to while loop except that checking condition expression is done at the end. That means code statements are executed at least once.

The conditional expression always results in the bool type and the possible values - true and false only.

if-else statements are used to execute statements based on true and false values.

Here is the syntax of the do-while loop.

do {
  //statements1
}while(conditional-expression1)

conditional-express results in a value of bool type.

First, statements are executed for the first time,

if the condition is true, statements are executed for multiple iterations. do and while are keywords that can not be used as identifiers in Dart Here is an example code for the do-while loop in Dart.

void main() {
  var number = 10;
  var sum = 0;

  do {
    sum = sum + number;
    number--;
  } while (number >= 1);
  print("The Sum is ${sum}");
}