for-in loop in Dart with example

Dart for-in loop :

The for-in loop is similar to normal for loop. It is used to iterate through the elements of an iterable class like a list or set. Unlike the normal for loop, where we need to add one condition for any iteration, for in loop can iterate through the elements of an iterable without any specific condition. Like it doesn’t need the length or any other variable to point to the current position.

In this blog post, I will show you how to use for in loop in dart with examples.

Syntax of for-in loop :

The syntax of for-in loop is as below :

for(item in collection){
    // statements
}

Example to loop through a list of elements using for-in :

Let’s loop through a list of strings using for-in :

main() {
  var numbers = ["one", "two", "three", "four", "five"];
  for (var item in numbers) {
    print(item);
  }
}

It will print :

one
two
three
four
five

Dart for-in list

Iterate through set elements :

We can also iterate through a set of elements similar to the above example :

main() {
  var values = {1, 3, 4, 5, 7, 7, 3, 1};
  for (var item in values) {
    print(item);
  }
}

It will print :

1
3
4
5
7

Dart for-in set

Duplicate items are removed from the set.

for-in loop makes it easier to iterate through a iterable. It is easier to write and clean than the conventional for loop.

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Don't forget to subscribe ❤️❤️🤩