Dart for..in Loop
Although its syntax is different, the for..in loop is comparable to the for loop. It goes over the attributes of an object one by one. The Dart for..in loop iterates through the elements one at a time in order, accepting an expression as an iterator. The values of the iteration are stored in the variable var. Until elements are still in iterators, the for…in will continue to run.
Dart For In Loop Flow Diagram
Syntax
for (var in expression) {
//statement(s)
}
Example
void main() {
var list1 = [10,20,30,40,50];
print("Dart for..in loop Example");
for(var i in list1) {
print(i);
}
}
Output
Dart for..in loop Example
10
20
30
40
50
Explanation
We have variable i and iterator list1 in the program mentioned above. The first item in the list was allocated to variable i in the loop’s initial iteration. This procedure was repeated, and this time, element two on the list was assigned to i. Until no element remains in the list, it will be carried out repeatedly. Every item in the list was printed to the console.
While the for loop is more efficient when iterating in conjunction with a given condition, the for..in loop is appropriate for iterating over Dart objects like lists, maps, and sets.
Example
void main() {
var list1 = [10,20,30,40,50];
// create an integer variable
int sum = 0;
print("Dart for..in loop Example");
for(var i in list1) {
// Each element of iterator and added to sum variable.
sum = i+ sum;
}
print("The sum is : ${sum}");
}
Output
Dart for..in loop Example
The sum is : 150
Explanation
We have defined a variable sum with value 0 in the example above. Every iteration of the for..in loop adds a new entry to the total variable, which is an iterator list.
The sum’s value on the first iteration is equal to 10. The value of total increased to 30 on the following iteration after 20 was added. The total of all the list’s elements was returned once the iteration was finished.