Bryn Flow

🎯 Dart Cheat Sheet

The syntax you look up over and over. Bookmark this page.

← Dart Track

Variables & Functions

var name = 'Ava';        // inferred
final age = 29;            // set once
const pi = 3.14159;        // compile-time constant

int square(int x) => x * x;
String greet(String name, {String greeting = 'Hi'}) => '$greeting, $name';

Null Safety

String? nickname;              // nullable
String display = nickname ?? 'Guest';
nickname!.toUpperCase();        // force unwrap
a ??= 'default';                 // assign if null
int? x;
x?.toString();                    // safe call

Collections

List<String> list = ['a', 'b'];
Set<int> set = {1, 2, 3};
Map<String, int> map = {'a': 1};

list.map((e) => e.toUpperCase()).toList();
list.where((e) => e.length > 1);
list.fold(0, (sum, e) => sum + e.length);

Classes

class Point {
  final double x, y;
  Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;
}

class Dog extends Animal with Swimmer {
  Dog(super.name);
  @override
  String speak() => '${super.speak()}, bark!';
}

mixin Swimmer { String swim() => 'swimming'; }

Async

Future<String> fetch() async {
  await Future.delayed(Duration(seconds: 1));
  return 'done';
}

try {
  final result = await fetch();
} catch (e) { }

final results = await Future.wait([fetch(), fetch()]);

Stream<int> count() async* {
  for (int i = 0; i < 3; i++) yield i;
}

Generics

class Box<T> {
  final T value;
  Box(this.value);
}

T firstOr<T>(List<T> items, T fallback) =>
    items.isEmpty ? fallback : items.first;

class NumBox<T extends num> { }  // bounded generic

Pattern Matching (Dart 3)

(String, int) record = ('Ava', 29);
final (name, age) = record;         // destructuring

String describe(Object v) => switch (v) {
  int n when n < 0 => 'negative',
  int n => 'number: $n',
  String s => 'string: $s',
  _ => 'unknown',
};

Want the full explanations?

Every item here is covered in depth on the Dart track.

Back to Dart Track