Dart for..in Loop

The for..in loop is similar to for loop but different in its syntax. It iterates through an object's properties. The Dart for..in loop accepts an expression as iterator and iterates through the elements one at a time in sequence. The variable var holds the values of the iteration. The for…in will execute until elements remain in iterators.

Dart For In Loop Flow Diagram

Dart for..in Loop

The syntax is given below.

Syntax:

Let's understand the following example.

Example -

Output:

Dart for..in loop Example
10
20
30
40
50

Explanation:

In the above program, we have iterator list1 and variable i. In the first iteration of the loop, the first element of the list assigned to the variable i. This process happened again, and the second element of the list assigned to i. It will be continued until there is no element left in the list. It printed the all element of the list to the console.

The for..in loop is suitable to iterate over the Dart object such as list, map, and set, where for loop is more effective to iterate along with the specified condition.

Let's understand another example.

Example -

Output:

Dart for..in loop Example
The sum is : 150

Explanation:

In the above example, we have declared a variable sum with value 0. We have a for..in loop with the iterator list, and each element of list added to the sum variable after each iteration.

In the first iteration, the value of the sum is equal to 10. In the next iteration, the value of sum became 30 after added 20 to it. After complete the iteration, it returned the sum of all elements of the list.


Next TopicDart While Loop




Latest Courses