Dart for in loop Code With Examples

2
10190
for in loop dart tutorial
Dart for in loop with examples

As the name suggests Dart for in loop is also a loop but a bit different than conventional for loop. It is mainly used to iterate over array’s or collection’s elements. The advantage for in loop has over the conventional for loop is clean code means fewer chances of error and more productivity. 

The for in loop iterate over the whole list but in each iteration only one value is assigned to the variable and loop continue until the whole list is traversed.

The syntax of for in loop in Dart looks like this.

  
 
for (DataType variableName in Array/collection ) {
  // code block to be executed
}
   

As the syntax and concept both are pretty easy to understand. Let’s take a code example. Suppose we have a List of subjects that we simply want to print. As we have value and later on any operation can be performed.

  
void main() {
  List subjects = ['Math', 'Biology', 'Economic', 'History', 'Science'];
  for (String sName in subjects) {
    print(sName);
  }
}
  

After code execution the output result is

  
Math
Biology
Economic
History
Science

List or collection could be any data type. In the last example we used a List with String values. This time consider a List with integer values and we want to print only the even numbers from the given list. Here we go.

  
void main() {
  List numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  for (int no in numbers) {
    if (no % 2 == 0) print(no);
  }
}

And the output of this piece of code is

  
2
4
6
8
10

Dart for in loop is so easy but a powerful concept to have. Now for in loop is pretty much explained.

2 COMMENTS

  1. How can i use 2 variables in for loop?
    For example I want to do the following:
    void main() {
    List subjects = [‘Math’, ‘Biology’];
    List icons = [icondata1, icondata2];
    for (String sName in subjects) {
    print(sName);
    }
    for (String sIcon in icons) {
    print(sIcon);
    }
    }
    I want to combine the for loops together and print (sName, sIcon)

    • Hi Fady,

      You don’t have to use two variable. There are different possible solutions. The simplest solution is to use a loop with an index.

      for (var i = 0; i < subjects.length; i++) { print('subject =${subjects[i]}, icon =${icons[i]}'); }

LEAVE A REPLY

Please enter your comment!
Please enter your name here