Dart List – Iterate over Elements

When working with lists, most of the times we may need to traverse or iterate through the elements of the list.

In this tutorial, we will learn some of the ways to iterate over elements of a Dart List.

Using for loop and index, you can start at the first element and end at the last element, incrementing the index from 0 to the length of the list.

Using List.forEach, you can apply a function for each element of the list.

You can get an iterable for list elements and use a while loop with iterable to iterate over the elements.

Iterate over Dart List using For Loop

In the following Dart Program, we take a list containing some elements. Then we use Dart For loop with index to traverse through all elements of the list. During each iteration, we just print the element, demonstrating that we can access the element.

Dart Program

</>
Copy
void main(){
	//list
	var myList = [25, 63, 84];
	
	//traverse through each element of list
	for(var i=0;i<myList.length;i++){
		print(myList[i]);
	}
}

Output

D:\tutorialkart\workspace\dart_tutorial>dart example.dart
25
63
84

Thus we can loop through list items using for loop.

Iterate over Dart List using forEach

In the following Dart Program, we apply print function for each element of the list.

Dart Program

</>
Copy
void main(){
	var myList = [24, 63, 84];
	
	myList.forEach((element) => 
		print(element)
	);
}

Output

D:\tutorialkart\workspace\dart_tutorial>dart example.dart
25
63
84

You can also apply a user defined function for each element instead of print function that we used in the above program.

Dart Program

</>
Copy
void processingFunc(var element){
	//processing or transformation on the element
	var x=element%2;
	print(x);
}

void main(){
	var myList = [24, 63, 84];
	
	myList.forEach((element) => 
		processingFunc(element)
	);
}

Output

D:\tutorialkart\workspace\dart_tutorial>dart example.dart
0
1
0

We just calculated the reminder when divided by 2, for each element in the list.

Iterate over Dart List using Iterator and While Loop

In the following Dart Program, we get the iterator to the list and store it in a variable. And then use this variable with while loop to move to the next element during each iteration and access the element. In this example, we just printed out the element.

Dart Program

</>
Copy
void main(){
	//list
	var myList = [25, 63, 84];
	
	//get iterator to the list
	var myListIter = myList.iterator;
	
	//iterate over the list
	while(myListIter.moveNext()){
		print(myListIter.current);
	}
}

Output

D:\tutorialkart\workspace\dart_tutorial>dart example.dart
25
63
84

Conclusion

In this Dart Tutorial, we learned how to iterate over elements of Dart List.