Dart For...in loop

In Dart, the for...in loop is used to iterate over elements in an iterable, such as lists, sets, or maps. It iterates over each element in the iterable and executes the loop body once for each element. The syntax of the for...in loop is as follows:
for (var item in iterable) {
// Statements to execute
}
Here's a breakdown of each part:
var item: This declares a variable (itemin this case) that represents each element in the iterable during each iteration of the loop.in: This keyword separates the variable declaration from the iterable being iterated over.iterable: This is the iterable object over which the loop iterates.
Here's an example of using the for...in loop to iterate over elements of a list:
var myList = [1, 2, 3, 4, 5];
for (var item in myList) {
print('Item: $item');
}
This loop iterates over each element in the list myList and prints its value:
Item: 1
Item: 2
Item: 3
Item: 4
Item: 5
You can also use the for...in loop with other iterable types, such as sets or maps. For sets, it iterates over each element in the set, and for maps, it iterates over each key-value pair in the map.
var mySet = {1, 2, 3, 4, 5};
for (var item in mySet) {
print('Item: $item');
}
var myMap = {'a': 1, 'b': 2, 'c': 3};
for (var key in myMap.keys) {
print('Key: $key, Value: ${myMap[key]}');
}
The for...in loop is a convenient way to iterate over the elements of an iterable in Dart, making your code more concise and readable.
About the author
I'm Computer Engineering Student. Learning Status DSA in Java, Dart Development, Python in Django Development. Best part is Communication Skills, Marketing, Accounting.
Comments
Join the discussionNo comments yet. Be the first to comment.




