5 Looping Collection
I’d be happy to guide you through Dart’s modern looping techniques! As someone with Python experience, you’ll find many similarities but also some important differences. Let’s explore Dart’s collection iteration methods and compare them with their Python counterparts.
5.1 The forEach()
Method in Dart
In Dart, the forEach()
method allows you to iterate through elements in a collection and perform an operation on each one.
void main() {
List<String> fruits = ['apple', 'banana', 'orange'];
// Using forEach
.forEach((fruit) {
fruits'I like $fruit');
print(});
// Using forEach with arrow syntax
.forEach((fruit) => print('I enjoy $fruit'));
fruits}
= ['apple', 'banana', 'orange']
fruits
# Using for loop
for fruit in fruits:
print(f'I like {fruit}')
# Using list comprehension (though this is for creating new lists, not just side effects)
print(f'I enjoy {fruit}') for fruit in fruits] [
The key difference is that Python’s for
loop is a statement, while Dart’s forEach()
takes a function as an argument. Python has no direct equivalent of forEach()
, though you could use the map()
function with a side effect.
5.2 The map()
Method in Dart
The map()
method transforms each element in a collection and returns a new iterable.
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
// Using map() to double each number
var doubled = numbers.map((number) => number * 2);
// (2, 4, 6, 8, 10) - returns an Iterable
print(doubled);
// Convert back to List
List<int> doubledList = doubled.toList();
// [2, 4, 6, 8, 10]
print(doubledList); }
= [1, 2, 3, 4, 5]
numbers
# Using map function with lambda
= map(lambda x: x * 2, numbers)
doubled print(list(doubled)) # [2, 4, 6, 8, 10]
# Using list comprehension (more common in Python)
= [x * 2 for x in numbers]
doubled_comp print(doubled_comp) # [2, 4, 6, 8, 10]
Notice that in Dart, map()
returns an Iterable
, not a List
. You need to call .toList()
to convert it. In Python, map()
returns a map object that needs to be converted to a list to display all elements.
5.3 The where()
Method in Dart (Similar to Python’s filter()
)
The where()
method filters elements that satisfy a condition.
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter even numbers
var evenNumbers = numbers.where((number) => number % 2 == 0);
.toList()); // [2, 4, 6, 8, 10]
print(evenNumbers}
= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers
# Using filter with lambda
= filter(lambda x: x % 2 == 0, numbers)
even_numbers print(list(even_numbers)) # [2, 4, 6, 8, 10]
# Using list comprehension (more common)
= [x for x in numbers if x % 2 == 0]
even_comp print(even_comp) # [2, 4, 6, 8, 10]
5.4 The reduce()
Method in Dart
The reduce()
method combines all elements in a collection using a function.
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
// Sum all numbers using reduce
int sum = numbers.reduce((value, element) => value + element);
// 15
print(sum);
// Find maximum value
int max = numbers.reduce((curr, next) => curr > next ? curr : next);
// 5
print(max); }
from functools import reduce
= [1, 2, 3, 4, 5]
numbers
# Using reduce
= reduce(lambda x, y: x + y, numbers)
sum_result print(sum_result) # 15
# More commonly in Python
print(sum(numbers)) # 15
print(max(numbers)) # 5
In Python, reduce()
needs to be imported from the functools
module, whereas in Dart it’s a built-in method on iterables.
5.5 Method Chaining in Dart
One powerful aspect of Dart’s collection methods is that they can be chained together:
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Chain multiple operations
var result = numbers
.where((n) => n % 2 == 0) // Get even numbers
.map((n) => n * n) // Square them
.toList(); // Convert to List
// [4, 16, 36, 64, 100]
print(result); }
= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers
# Using functional approach (less common)
= list(map(lambda x: x * x, filter(lambda x: x % 2 == 0, numbers)))
result
# More Pythonic approach with comprehension
= [x * x for x in numbers if x % 2 == 0]
result
print(result) # [4, 16, 36, 64, 100]
5.6 The fold()
Method in Dart
The fold()
method is similar to reduce()
but allows you to specify an initial value and return a different type.
void main() {
List<String> words = ['Hello', 'Dart', 'Programming'];
// Count total characters using fold
int totalChars = words.fold(0, (prev, word) => prev + word.length);
// 19
print(totalChars);
// Join all words with a space
String joined = words.fold('', (prev, word) => prev + (prev.isEmpty ? '' : ' ') + word);
// "Hello Dart Programming"
print(joined); }
= ['Hello', 'Dart', 'Programming']
words
# Using reduce for character count
from functools import reduce
= reduce(lambda acc, word: acc + len(word), words, 0)
total_chars print(total_chars) # 19
# More Pythonic way
= sum(len(word) for word in words)
total_chars print(total_chars) # 19
# Joining words
= ' '.join(words)
joined print(joined) # "Hello Dart Programming"