Dart collection methods are powerful tools for manipulating and transforming data in lists, sets, and maps. These methods provide a concise and efficient way to perform common operations on collections, enhancing code readability and reducing complexity.
The forEach()
method allows you to iterate over each element in a collection and perform an action.
List<int> numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => print(number));
Use map()
to transform each element in a collection and create a new iterable.
List<int> numbers = [1, 2, 3, 4, 5];
var doubled = numbers.map((number) => number * 2);
print(doubled); // (2, 4, 6, 8, 10)
The where()
method filters elements based on a condition, returning a new iterable.
List<int> numbers = [1, 2, 3, 4, 5];
var evenNumbers = numbers.where((number) => number % 2 == 0);
print(evenNumbers); // (2, 4)
reduce()
combines all elements in a collection into a single value.
List<int> numbers = [1, 2, 3, 4, 5];
var sum = numbers.reduce((value, element) => value + element);
print(sum); // 15
Similar to reduce()
, but fold()
allows you to specify an initial value and return a different type.
List<String> words = ['Dart', 'is', 'awesome'];
var sentence = words.fold('', (prev, element) => '$prev $element');
print(sentence.trim()); // "Dart is awesome"
To further enhance your understanding of Dart collections and their methods, explore these related topics:
Mastering Dart collection methods will significantly improve your ability to manipulate data efficiently in your Dart programs. These methods are essential for working with Dart for Flutter applications and other Dart projects.