Dart
01 / 02

Types, Null Safety, Classes & Collections

Types, Null Safety, Classes & Collections

Variables & Null Safety

int count = 5;
var name = "Ada";        // inferred as String
String? nickname;         // nullable — can hold null
String description = nickname ?? "no nickname";  // null-coalescing fallback

final DateTime now = DateTime.now();  // runtime value, assigned once
// const DateTime x = DateTime.now();  // ERROR — not a compile-time constant

Sound null safety means a non-nullable type (String) can never actually be null — the compiler proves it via control-flow analysis, catching a whole class of null-reference bugs before runtime. final locks a value after first (runtime) assignment; const requires a compile-time-known value.

Classes, Inheritance & Enums

class Animal {
  String name;
  Animal(this.name);          // constructor shorthand
  void speak() => print('...');
}

class Dog extends Animal {
  Dog(String name) : super(name);
  @override
  void speak() => print('Woof!');
}

enum Status { active, inactive, pending }

Named Parameters, Collections & Errors

void greet({required String name, String greeting = 'Hello'}) {
  print('$greeting, $name!');
}
greet(name: 'Ada');

List<int> numbers = [1, 2, 3];
Map<String, int> ages = {'Ada': 30};

try {
  riskyOperation();
} on FormatException catch (e) {
  print('Bad format: $e');
} finally {
  cleanup();
}

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free