Dart: List, Map, Set and Functional Methods

map(), where(), reduce() and fold() — everyday bread and butter in Flutter

📋 1. List and functional methods

Result:

numeros
[1, 2, 3, 4, 5, 5, 3]
.map((n) => n * 2)
[2, 4, 6, 8, 10, 10, 6]
.where((n) => n > 3)
[4, 5, 5]
.reduce((a, b) => a + b)
23
.fold(0, (a, b) => a + b)
23
Set (no duplicates)
{1, 2, 3, 4, 5}

Try with your own numbers

final numeros = [1, 2, 3, 4, 5, 5, 3];

final mapeados  = numeros.map((n) => n * 2).toList();
final filtrados = numeros.where((n) => n > 3).toList();
final suma      = numeros.reduce((a, b) => a + b);
final total     = numeros.fold(0, (acc, n) => acc + n);
final unicos    = numeros.toSet(); // elimina duplicados
// Spread operator: combinar listasfinal combinada = [0, ...numeros, 100];
💡 reduce() vs fold()

reduce() uses the first element as the initial value (it fails if the list is empty). fold() receives an explicit initial value (here 0), so it works even with empty lists.

🗂️ 2. Map (key-value)

Result:

manzana
3
pera
5
uva
12
containsKey('pera')
true

Try with your own map

final frutas = {'manzana': 3, 'pera': 5, 'uva': 12};

frutas.forEach((clave, valor) => print('$clave: $valor'));

for (final entrada in frutas.entries) {
  print('${entrada.key} -> ${entrada.value}');
}

print(frutas.containsKey('pera')); // true

🎯 Key Concepts

List

  • Ordered, allows duplicates
  • [...] to create it, const [...] if it's immutable

Map

  • Key-value pairs
  • .entries, .keys, .values

Set

  • No duplicates, no guaranteed order
  • {...} o .toSet()

💪 Practical Exercise

Combine the functional methods

  1. Starting from a list of names, use .where() to keep only the ones that start with a specific letter.
  2. Use .map() followed by .join(', ') to build a sentence with the VAT-inclusive prices of a list.
  3. Use the spread operator (...) to insert the elements of one list into another.

Solution 1

final nombres = ['Ana', 'Luis', 'Andrea', 'Marta'];
final conA = nombres.where((n) => n.startsWith('A')).toList();

Solution 2

final precios = [10, 25, 50];
final frase = precios.map((p) => '${(p * 1.21).toStringAsFixed(2)}€').join(', ');

Solution 3

final base = [2, 3];
final extendida = [1, ...base, 4]; // [1, 2, 3, 4]