For-In Loop

The for-in loop is a convenient way to iterate through collections like lists, sets, maps, and strings in Dart. It's perfect when you want to access each element in a collection without worrying about indices or manual iteration.

Think of it like going through your playlist - you don't need to know the track numbers, you just want to listen to each song one by one!

Basic Syntax

for (dataType variable in collection) {
  // Code to execute for each element
}

Iterating Through Lists

The most common use case is iterating through lists:

void main() {
  List<String> fruits = ['apple', 'banana', 'orange', 'mango'];
  
  for (String fruit in fruits) {
    print('I love $fruit!');
  }
}

Output:

I love apple!
I love banana!
I love orange!
I love mango!

Iterating Through Strings

You can also iterate through each character in a string:

void main() {
  String word = 'Dart';
  
  for (String char in word.split('')) {
    print('Character: $char');
  }
}

Output:

Character: D
Character: a
Character: r
Character: t

Iterating Through Sets

Sets work just like lists with for-in loops:

void main() {
  Set<int> numbers = {1, 2, 3, 4, 5};
  
  for (int number in numbers) {
    print('Number: $number');
  }
}

Iterating Through Maps

For maps, you can iterate through keys, values, or entries:

void main() {
  Map<String, int> ages = {
    'Alice': 25,
    'Bob': 30,
    'Charlie': 35
  };
  
  // Iterate through keys
  for (String name in ages.keys) {
    print('Name: $name');
  }
  
  // Iterate through values
  for (int age in ages.values) {
    print('Age: $age');
  }
  
  // Iterate through entries (key-value pairs)
  for (MapEntry<String, int> entry in ages.entries) {
    print('${entry.key} is ${entry.value} years old');
  }
}

Type Inference with var

Dart can automatically infer the type, so you can use var instead of specifying the exact type:

void main() {
  List<String> colors = ['red', 'green', 'blue'];
  
  for (var color in colors) {  // Dart knows color is String
    print('Color: $color');
  }
}

When to Use For-In Loop

The for-in loop is ideal when:

  • You need to access each element in a collection
  • You don't need the index of elements
  • You want clean, readable code
  • You're working with any iterable collection