Warning: Undefined array key "lang_code" in /home/pmfnldmy/public_html/androidatc/ap/extension/classes/common.php on line 800
Dart Programming - While Loops

While Loops

A while-statement depends on a Boolean expression and its counter. If the expression proves to be true, the While statement executes the statement(s) in the While block. The while statement continues testing the expression and executing its loop until the expression is proved false.

The following example explains how While loops work:

main() {

  var x=1;
  while (x<=5)
  {
   print("x= $x");
    x++;  
// this is the counter for the loop means x=x+1 i.e. increment x by 1 
//each time
  }
}


The following steps illustrate the flow of execution of the previous code:
1- The initial value of integer variable named x as 1.
2- The compiler checks the condition (x < =5) which proves to be true, so it moves
into the code block of the While statement and prints "x=1".
3- The counter variable is incremented to value 1 and the compiler loops to the top.
4- The compiler checks again the While loop condition (x < =5) which proves to be
true, so the compiler prints "x=2" and increments the counter variable to value 2.
5- The program will continue working until it reaches x=6. After that the compiler checks again the While loop condition (x < =5) and proves to be false, the compiler will skip the code block and move forward to execute the code of the statements that follows the While statement.

When you run the Dart program, you will get the following result:

While Loops

* This topic is a part of lesson 2 of Flutter Application Development course. For more information about this course, click here.