Dart: Variables, Types and Null Safety
var, final, const, and the operators ?, !, ??, ??= that make Dart a "null-safe"
🎯 Demo 1: Operators for Null Safety
Result:
Try with and without a value
String? nombre = obtenerNombre(); // puede ser null
String saludo = nombre ?? 'Invitado'; // si nombre es null, usa 'Invitado'
int longitud = nombre?.length ?? 0; // ?. evita el error si nombre es null
// nombre! le dice al compilador "confía en mí, no es null" — si SÍ lo es, explota en runtime:
print(nombre!.length); // Unhandled exception: Null check operator used on a null value
💡 Null safety en Dart
Since Dart 2.12, a type like String can NEVER be null — to allow it you have to write String? explicitly. This eliminates an entire class of errors at compile time ("null pointer") that in other languages are only caught in production.
🔒 Demo 2: var vs final vs const
Result:
Try reassigning a final
var edad = 25; // el TIPO se infiere (int) pero la variable sí se puede reasignaredad = 26; // correcto
final colorFavorito = 'azul'; // se asigna una vez, ya no se puede cambiarcolorFavorito = 'verde'; // Error de compilación
const pi = 3.14159; // como final, pero el valor debe conocerse en tiempo de COMPILACIÓN
💡 ¿final o const?
Use const when the value is a constant known ahead of time (e.g. a fixed number). Use final when the value is calculated at runtime but shouldn't change afterward (e.g. the current time, a function's result).
🎯 Key Concepts
var / final / const
var: reassignable, inferred typefinal: assigned onceconst: compile-time constant
Null safety
Tipo?allows null,Tipodoes not??default value?.safe access
late
- Promises to initialize later
- Error if read before being assigned
💪 Practical Exercise
Practice null safety
- Declare
int? edad;with no initial value and useedad ??= 18;to assign it a value only if it's still null. - Create a variable
late String apellido;and assign it a value before using it for the first time. - Write a function that takes
String? textoand returns its length using?.and??in a single line.
Solution 1
int? edad;
edad ??= 18; // como edad era null, ahora edad vale 18
Solution 2
late String apellido;
apellido = 'Gómez'; // debe asignarse antes del primer uso
Solution 3
int longitudDe(String? texto) => texto?.length ?? 0;