Dart: Functions, Parameters and Closures

Named/optional parameters, arrow functions and functions that remember their own state

🏷️ 1. Named and Optional Parameters

Result:

saludar(nombre: ..., edad: ...)
Hi, Guest!

Call the function

String saludar({String nombre = 'Invitado', int? edad}) {
  final edadTexto = edad != null ? ' ($edad años)' : '';
  return 'Hola, $nombre$edadTexto!';
}

saludar();                      // Hola, Invitado!
saludar(nombre: 'Jorge');       // Hola, Jorge!
saludar(nombre: 'Jorge', edad: 30); // Hola, Jorge (30 años)!
💡 { } vs [ ]

Parameters between { } are named (they're called by their name, in any order). Parameters between [ ] are optional positional. Both can have a default value with = valor, or be nullable with ?.

➡️ 2. Arrow Functions

Result:

cuadrado(5)
25

Try a number

// Función normalint cuadrado(int x) {
  return x * x;
}

// La misma función, como arrow function (una sola expresión)int cuadrado(int x) => x * x;

🔐 3. Closures (functions that remember their state)

Current counter state:

incrementar()
Valor actual: 0

Call the closure several times

Function crearContador() {
  int valor = 0;           // esta variable vive "encerrada" dentro del closure  return () {
    valor++;
    return valor;
  };
}

final incrementar = crearContador();
print(incrementar()); // 1
print(incrementar()); // 2
print(incrementar()); // 3 (recuerda el valor entre llamadas)
💡 ¿Qué es un closure?

It's a function that "captures" variables from its surrounding scope and keeps them alive even after the function that created them has finished running. Each call to crearContador() would generate an independent counter with its own state.

🎯 Key Concepts

Named Parameters

  • {String nombre = '...'}
  • Called by name: fn(nombre: 'x')

Arrow functions

  • => expresion;
  • Only for a single return expression

Closures

  • Capture variables from the surrounding scope
  • Maintain state between calls

💪 Practical Exercise

Practice functions

  1. Create String formatear(String texto, {bool mayusculas = false}) that returns the text in uppercase if indicated.
  2. Convert a two-parameter sum function into an arrow function.
  3. Create a closure crearMultiplicador(int factor) that returns a function that multiplies any number by that factor.

Solution 1

String formatear(String texto, {bool mayusculas = false}) {
  return mayusculas ? texto.toUpperCase() : texto;
}

Solution 2

int sumar(int a, int b) => a + b;

Solution 3

Function(int) crearMultiplicador(int factor) {
  return (int n) => n * factor;
}

final porTres = crearMultiplicador(3);
print(porTres(5)); // 15