Fundamentos
Hola Mundo
void main() { print('Hello, Dart!'); }
Variables
var name = 'Dart'; // tipo inferido String lang = 'Dart'; // tipo explícito final pi = 3.14; // constante en tiempo de ejecución const max = 100; // constante en tiempo de compilación
Interpolación de Cadenas
var name = 'World'; print('Hello, $name!'); print('1 + 1 = ${1 + 1}');
Tipos
Tipos Integrados
intEntero de 64 bits
doublePunto flotante de 64 bits
numSupertipo de int y double
StringCadena UTF-16
booltrue o false
ListColección ordenada (arreglo)
SetColección única desordenada
MapPares clave-valor
dynamicCualquier tipo, deshabilita verificación estática
voidSin valor de retorno
Verificación y Conversión de Tipos
if (obj is String) print(obj.length); var s = obj as String; // conversión print(obj.runtimeType); // tipo en tiempo de ejecución
Funciones
Sintaxis de Función
int add(int a, int b) => a + b; void greet({required String name}) { print('Hello, $name'); }
Parámetros
int f(int a)Parámetro posicional requerido
int f([int a = 0])Posicional opcional con valor por defecto
f({required int a})Parámetro con nombre requerido
f({int a = 0})Con nombre opcional y valor por defecto
Closures y Tearoffs
var square = (int n) => n * n; [1, 2, 3].map((e) => e * 2); [1, 2, 3].forEach(print); // tearoff
Control de Flujo
Condicionales
if (x > 0) { print('pos'); } else if (x == 0) { print('zero'); } else { print('neg'); } var result = x > 0 ? 'pos' : 'neg';
Bucles
for (var i = 0; i < 5; i++) { } for (var item in list) { } while (x > 0) { x--; } do { x--; } while (x > 0);
Switch y Pattern Matching
switch (color) { case 'red': print('R'); break; case 'blue': print('B'); break; default: print('?'); }
Clases
Definición de Clase
class Point { final double x, y; Point(this.x, this.y); double distanceTo(Point p) => sqrt(pow(x - p.x, 2) + pow(y - p.y, 2)); }
Constructores con Nombre y Factory
class Point { double x, y; Point(this.x, this.y); Point.origin() : x = 0, y = 0; factory Point.fromJson(Map j) => Point(j['x'], j['y']); }
Herencia
class Animal { void speak() {} } class Dog extends Animal { @override void speak() => print('Woof'); }
Mixins y Extensiones
Mixins
mixin Flyable { void fly() => print('Flying'); } class Bird with Flyable {}
Métodos de Extensión
extension StringX on String { String capitalize() => '${this[0].toUpperCase()}${substring(1)}'; } print('hello'.capitalize()); // Hello
Abstract e Implements
abstract class Shape { double area(); } class Circle implements Shape { final double r; Circle(this.r); @override double area() => pi * r * r; }
Async/Await
Futures
Future fetchData() async { var res = await http.get(uri); return res.body; }
Streams
Stream count(int n) async* { for (var i = 0; i < n; i++) { yield i; } }
Manejo de Errores
try { var data = await fetchData(); } on HttpException catch (e) { print('HTTP error: $e'); } catch (e) { print('Error: $e'); }
Colecciones
Operaciones con List
var nums = [1, 2, 3]; nums.add(4); nums.where((n) => n > 2); // [3, 4] nums.map((n) => n * 2); // [2,4,6,8] var sorted = nums..sort();
Operaciones con Map
var m = {'a': 1, 'b': 2}; m['c'] = 3; m.containsKey('a'); // true m.entries.map((e) => '${e.key}=${e.value}');
Spread y Collection If/For
var all = [0, ...nums]; var nav = ['Home', if (isAdmin) 'Admin']; var sq = [for (var i in nums) i * i];
Null Safety
Tipos Nullable
int?int nullable (puede ser null)
intint no nullable (nunca null)
!Operador de aserción null
?.Acceso null-aware
??Valor por defecto si null
??=Asignar si null
lateInicialización diferida
Ejemplos de Null Safety
String? name; // nullable int len = name?.length ?? 0; late final String title; // asignar antes de usar name ??= 'default'; // asignar si null
Patrones Comunes
Enum con Valores
enum Color { red('FF0000'), green('00FF00'); final String hex; const Color(this.hex); }
Records y Destructuring
(String, int) userInfo() => ('Alice', 30); var (name, age) = userInfo(); print('$name is $age');
Sealed Classes
sealed class Shape {} class Circle extends Shape { final double r; Circle(this.r); } class Rect extends Shape { final double w, h; Rect(this.w, this.h); }