Dart – Iterate over Elements of Set using Set.forEach()

To iterate over elements of a Set in Dart, we can use Set.forEach() method. During each iteration, respective element can be accessed inside the forEach block.

Syntax

The syntax to iterate over elements of Set mySet using forEach() method is

mySet.forEach((element) {
  //code
});
ADVERTISEMENT

Examples

In the following program, we take a Set mySet, iterate over the elements using forEach() method, and print each element to console.

main.dart

void main() {
  Set mySet = {'apple', 'banana', 'cherry'};
  mySet.forEach((element) {
    print(element);
  });
}

Output

apple
banana
cherry

Conclusion

In this Dart Tutorial, we learned how to iterate over the elements of a Set in Dart language, using Set.forEach() method, with examples.