Dart
Collections (List, Map, Set)
Work with collections and functional operations.
By EZ4Code Team
listmapset
Code
// List
var nums = [1, 2, 3, 4, 5];
nums.add(6);
nums.addAll([7, 8]);
var doubled = nums.map((n) => n * 2).toList();
var evens = nums.where((n) => n % 2 == 0).toList();
var sum = nums.reduce((a, b) => a + b);
var firstEven = nums.firstWhere((n) => n % 2 == 0, orElse: () => -1);
// Spread operator
var combined = [...nums, ...[9, 10]];
// Map
var ages = {'Alice': 30, 'Bob': 25};
ages['Carol'] = 28;
ages.forEach((k, v) => print('$k: $v'));
var adults = ages.entries.where((e) => e.value >= 18).map((e) => e.key).toList();
// Set
var unique = <int>{1, 2, 2, 3, 3, 3}; // {1, 2, 3}
unique.add(4);
unique.contains(2); // true
// Collection if/for (Dart 3)
var showExtra = true;
var items = [
'item1',
'item2',
if (showExtra) 'extra',
for (var i = 0; i < 3; i++) 'gen$i',
];Explanation
Dart collections support functional methods (map, where, reduce, fold). map returns a lazy Iterable — call toList() to materialize. Collection if/for (Dart 3) lets you conditionally include elements inline. Spread (...) flattens. firstWhere throws if no match — use orElse. Sets dedupe automatically. Use const collections for compile-time constants.
More Dart Snippets
Classes and Constructors
Define classes with named and factory constructors.
Async/Await and Futures
Asynchronous programming with Future and async/await.
Null Safety
Sound null safety with ? and ! operators.
Generics
Type-safe reusable classes and methods.
Mixins and Extensions
Compose behaviors without inheritance.
Futures and Streams
Work with single and multiple async values.