Dart Loops

Dart Loop is used to run a block of code repetitively for a given number of times or until matches the specified condition. Loops are essential tools for any programming language. It is used to iterate the Dart iterable such as list, map, etc. and perform operations for multiple times. A loop can have two parts - a body of the loop and control statements. The main objective of the loop is to run the code multiple times. Dart supports the following type of loops.

  • Dart for loop
  • Dart for…in loop
  • Dart while loop
  • Dart do-while loop

We describe a brief introduction to the dart loops as follows.

Dart for loop

The for loop is used when we know how many times a block of code will execute. It is quite same as the C for loop. The syntax is given below.

Syntax -

The loop iteration starts from the initial value. It executes only once.

The condition is a test-expression and it is checked after each iteration. The for loop will execute until false returned by the given condition.

The incr/decr is the counter to increase or decrease the value.

Let's understand the following example.

Example -

Output:

1
2
3
4
5
6
7
8
9
10

Dart for… in Loop

The for…in loop is slightly different from the for loop. It only takes dart object or expression as an iterator and iterates the element one at a time. The value of the element is bound to var, which is and valid and available for the loop body. The loop will execute until no element left in the iterator. The syntax is given below.

Syntax -

Example :

Output:

10
20
30
40
50

We need to declare the iterator variable to get the element from the iterator.

Dart while loop

The while loop executes a block of code until the given expression is false. It is more beneficial when we don't know the number of execution. The syntax is given below.

Syntax:

Let's understand the following example.

Example -

Output:

1
2
3
4
5
6
7
8
9

Dart do…while Loop

The do…while loop is similar to the while loop but only difference is that, it executes the loop statement and then check the given condition. The syntax is given below.

Syntax -

Example -

Output:

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5
The value is: 6
The value is: 7
The value is: 8
The value is: 9

Selection of the loop

The selection of a loop is a little bit difficult task to the programmer. It is hard to decide which loop will be more suitable to perform a specific task. We can determine the loop based on the following points.

  • Analyze the problem and observe that whether you need a pre-test loop or post-test loop. A pre-test loop is that, the condition is tested before entering the loop. In the post-test loop, the condition is tested after entering the loop.
  • If we require a pre-test loop, then select the while or for loop.
  • If we require a post-test loop, then select the do-while loop.

Next TopicDart for Loop