Collections & Loops

Dart lists, sets, maps, and iteration patterns.

List

Ordered collection with duplicates allowed.

// Creating
var list = [1, 2, 3];                      // List<int>
var mutable = <int>[1, 2, 3];               // growable list
var fixed = List.filled(3, 0);               // [0, 0, 0] — fixed length
var empty = <int>[];                         // empty list

// Spread and null-aware spread
var a = [1, 2];
var b = [0, ...a, 3];                        // [0, 1, 2, 3]
List<int>? maybeNull;
var c = [0, ...?maybeNull, 3];               // [0, 3] if maybeNull is null

// Collection if and for (inside literals)
var active = true;
var items = [1, if (active) 2, 3];            // [1, 2, 3]

var indices = [for (var i = 0; i < 3; i++) i]; // [0, 1, 2]

// Access
list[0];                      // 1
list.last;                     // 3
list.length;                   // 3

// Add / remove (growable only)
mutable.add(4);                // [1, 2, 3, 4]
mutable.addAll([5, 6]);       // [1, 2, 3, 4, 5, 6]
mutable.insert(0, 0);         // [0, 1, 2, 3, 4, 5, 6]
mutable.removeLast();          // removes 6
mutable.remove(3);            // removes value 3
mutable.removeAt(0);          // removes element at index 0

// Transform
list.map((e) => e * 2);                   // [2, 4, 6]
list.where((e) => e > 1);                  // [2, 3]
list.expand((e) => [e, e]);                // [1, 1, 2, 2, 3, 3]

// Sort
var nums = [3, 1, 2];
nums.sort();                                 // [1, 2, 3]
nums.sort((a, b) => b.compareTo(a));         // [3, 2, 1]

// Find
list.firstWhere((e) => e > 1, orElse: () => -1);  // 2
list.lastWhere((e) => e > 1, orElse: () => -1);     // 3
list.indexWhere((e) => e > 1);                      // 1
list.any((e) => e > 2);                              // true
list.every((e) => e > 0);                            // true

// Reduce / fold
list.reduce((a, b) => a + b);               // 6
list.fold<int>(0, (acc, e) => acc + e);     // 6

// Join to string
list.join(', ');                              // '1, 2, 3'

Set

Unordered collection with unique elements.

// Creating
var set = {1, 2, 3};                     // Set<int>
var emptySet = <int>{};                   // empty Set (not a map!)
var fromList = {1, 2, 2, 3};             // {1, 2, 3} — duplicates removed

// Add / remove
set.add(4);                               // {1, 2, 3, 4}
set.addAll([5, 6]);                      // {1, 2, 3, 4, 5, 6}
set.remove(1);                            // {2, 3, 4, 5, 6}

// Check membership
set.contains(2);                          // true

// Set operations
var a = {1, 2, 3};
var b = {2, 3, 4};

a.union(b);                               // {1, 2, 3, 4}
a.intersection(b);                        // {2, 3}
a.difference(b);                           // {1}

Map

Key-value pairs. Keys are unique.

// Creating
var map = {'a': 1, 'b': 2, 'c': 3};     // Map<String, int>
var mutable = <String, int>{};            // empty mutable map
var empty = Map<String, int>();            // empty map

// Access
map['a'];                                  // 1 — returns null if missing
map['z'] ?? 0;                             // 0 — default if missing

// Add / update
mutable['x'] = 10;                         // add or update
mutable.addAll({'y': 20, 'z': 30});        // add all
mutable.update('x', (v) => v * 2);         // update existing
mutable.putIfAbsent('w', () => 40);        // add only if missing

// Remove
mutable.remove('w');                        // removes key, returns value or null

// Iterate
for (var key in map.keys) {
  print(key);
}

for (var value in map.values) {
  print(value);
}

map.forEach((key, value) {
  print('$key = $value');
});

// Transform
map.map((key, value) => MapEntry(key.toUpperCase(), value * 2));

// Filter
map.entries.where((e) => e.value > 1).toList();

Loops

Classic for

for (var i = 0; i < 10; i++) {
  print(i);
}

for-in (collections)

for (var item in list) {
  print(item);
}

while

var running = true;
while (running) {
  if (done()) {
    running = false;
  }
}

do-while

do {
  process();
} while (!finished);

break & continue

for (var i = 0; i < 10; i++) {
  if (i % 2 == 0) continue;    // skip even
  if (i > 7) break;             // stop at 8
  print(i);
}

Next: Classes & Mixins