Basi
Hello World
void main() { print('Hello, Dart!'); }
Variabili
var name = 'Dart'; // tipo inferito String lang = 'Dart'; // tipo esplicito final pi = 3.14; // costante runtime const max = 100; // costante compile-time
Interpolazione di Stringhe
var name = 'World'; print('Hello, $name!'); print('1 + 1 = ${1 + 1}');
Tipi
Tipi Predefiniti
intIntero a 64 bit
doubleVirgola mobile a 64 bit
numSupertipo di int e double
StringStringa UTF-16
booltrue o false
ListCollezione ordinata (array)
SetCollezione unica non ordinata
MapCoppie chiave-valore
dynamicQualsiasi tipo, disabilita il controllo statico
voidNessun valore di ritorno
Controllo Tipo e Cast
if (obj is String) print(obj.length); var s = obj as String; // cast print(obj.runtimeType); // tipo a runtime
Funzioni
Sintassi delle Funzioni
int add(int a, int b) => a + b; void greet({required String name}) { print('Hello, $name'); }
Parametri
int f(int a)Parametro posizionale obbligatorio
int f([int a = 0])Posizionale opzionale con default
f({required int a})Parametro nominato obbligatorio
f({int a = 0})Nominato opzionale con default
Closure e Tearoff
var square = (int n) => n * n; [1, 2, 3].map((e) => e * 2); [1, 2, 3].forEach(print); // tearoff
Controllo del Flusso
Condizionali
if (x > 0) { print('pos'); } else if (x == 0) { print('zero'); } else { print('neg'); } var result = x > 0 ? 'pos' : 'neg';
Cicli
for (var i = 0; i < 5; i++) { } for (var item in list) { } while (x > 0) { x--; } do { x--; } while (x > 0);
Switch e Pattern Matching
switch (color) { case 'red': print('R'); break; case 'blue': print('B'); break; default: print('?'); }
Classi
Definizione di Classe
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)); }
Costruttori Nominati e 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']); }
Ereditarietà
class Animal { void speak() {} } class Dog extends Animal { @override void speak() => print('Woof'); }
Mixin ed Extension
Mixin
mixin Flyable { void fly() => print('Flying'); } class Bird with Flyable {}
Metodi di Estensione
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
Future
Future fetchData() async { var res = await http.get(uri); return res.body; }
Stream
Stream count(int n) async* { for (var i = 0; i < n; i++) { yield i; } }
Gestione Errori
try { var data = await fetchData(); } on HttpException catch (e) { print('HTTP error: $e'); } catch (e) { print('Error: $e'); }
Collezioni
Operazioni su 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();
Operazioni su Map
var m = {'a': 1, 'b': 2}; m['c'] = 3; m.containsKey('a'); // true m.entries.map((e) => '${e.key}=${e.value}');
Spread e Collection If/For
var all = [0, ...nums]; var nav = ['Home', if (isAdmin) 'Admin']; var sq = [for (var i in nums) i * i];
Null Safety
Tipi Nullable
int?int nullable (può essere null)
intint non-nullable (mai null)
!Operatore di asserzione null
?.Accesso null-aware
??Default se null
??=Assegna se null
lateInizializzazione differita
Esempi Null Safety
String? name; // nullable int len = name?.length ?? 0; late final String title; // impostato prima dell'uso name ??= 'default'; // assegna se null
Pattern Comuni
Enum con Valori
enum Color { red('FF0000'), green('00FF00'); final String hex; const Color(this.hex); }
Record e Destructuring
(String, int) userInfo() => ('Alice', 30); var (name, age) = userInfo(); print('$name is $age');
Classi Sealed
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); }