Dart Null Safety, Records, and Pattern Matching Explained

Dart 3 turns three separate features into one workflow. Sound null safety removes null-reference crashes at compile time. Records return multiple values without a throwaway class. Pattern matching destructures and validates data in a single expression. Used together, they replace pages of if/is/cast boilerplate with short, exhaustive, compiler-checked code.

Quick Takeaways

  • Null safety splits every type into non-nullable (String) and nullable (String?). The compiler blocks unsafe access before runtime.
  • Records are anonymous, immutable, structurally typed aggregates such as (int, String) or ({int id, String name}).
  • Patterns destructure values in switch, if-case, and variable declarations. Combined with sealed classes, they give you compile-time exhaustiveness checking.
  • Prefer flow-analysis promotion and patterns over the bang operator (!). Each ! is a deferred runtime crash.
Feature Introduced Solves Runtime Cost Key Syntax
Sound null safety Dart 2.12 Null dereference errors None (compile-time) String?, ?., ??, late
Records Dart 3.0 Multi-value returns, ad hoc grouping Low (lightweight immutable value) (a, b), (x: 1, y: 2)
Patterns Dart 3.0 Verbose type checks and destructuring Compiled to checks and tests case, switch, when, =>
Sealed classes Dart 3.0 Closed type hierarchies None sealed class

Dart Null Safety: The Foundation

In Dart, a type is non-nullable by default. String name can never hold null. To allow it, you opt in with String? name.

void main() {
  String title = 'Dart';   // Non-nullable: must always hold a String
  String? subtitle;        // Nullable: defaults to null

  // title = null;         // Compile-time error
  subtitle = 'Records';    // OK
}

The compiler rejects the commented-out line. The runtime never sees a null title.

Null-Aware Operators

Dart gives you a compact toolkit for nullable values.

Operator Name Behavior Example
?. Null-aware access Short-circuits to null if the receiver is null user?.name
?? If-null Returns the right side when the left is null name ?? 'Guest'
??= Null-aware assignment Assigns only if the variable is null cache ??= load()
! Null assertion Casts to non-nullable, throws if null value!
...? Null-aware spread Spreads a collection only if non-null [...?extras]
String displayName(String? name) {
  // Evaluates to 'Guest' when name is null
  return name?.trim() ?? 'Guest';
}

void main() {
  print(displayName('  Ada  ')); // Ada
  print(displayName(null));      // Guest
}

The first call trims the string and returns Ada. The second short-circuits at ?., yields null, then ?? supplies Guest.

Type Promotion and Flow Analysis

Dart’s flow analysis tracks null checks and promotes a nullable variable to its non-nullable type inside the safe branch.

int safeLength(String? input) {
  if (input == null) return 0;   // Early exit
  return input.length;           // input is promoted to String here
}

No bang operator is needed. After the early return, the compiler knows input is a String.

Promotion has limits. It works on local variables and, since Dart 3.2, on private final fields. It does not work on public or mutable fields, because another piece of code could change them between the check and the use.

class Session {
  final String? _token;
  Session(this._token);

  int tokenLength() {
    if (_token == null) return 0;
    return _token.length; // Promoted: private final field (Dart 3.2+)
  }
}

For a mutable field, copy it into a local variable first:

class Profile {
  String? nickname;

  String shout() {
    final n = nickname;          // Local snapshot
    if (n == null) return '';
    return n.toUpperCase();      // Promoted safely
  }
}

late and required

The late modifier defers initialization while keeping the type non-nullable. Reading it before assignment throws a LateInitializationError.

class Report {
  // Computed once, on first access
  late final String summary = _buildSummary();

  String _buildSummary() => 'Generated at ${DateTime.now()}';
}

The initializer runs lazily and only once. For named parameters, required forces callers to pass a value instead of silently defaulting to null:

class User {
  final String id;
  final String? email; // Genuinely optional

  User({required this.id, this.email});
}

Dart Records: Lightweight Multi-Value Types

A record groups values into one immutable object without declaring a class. Records have structural typing. Their shape defines their type.

Positional and Named Fields

void main() {
  // Positional record: type is (String, int)
  var point = ('origin', 0);

  // Named record: type is ({String name, int age})
  var user = (name: 'Ada', age: 36);

  // Mixed record: (int, {String label})
  var tagged = (7, label: 'lucky');

  print(point.$1);     // origin
  print(user.name);    // Ada
  print(tagged.$1);    // 7
  print(tagged.label); // lucky
}

Positional fields use the getters $1, $2, and so on. Named fields use their own names. Positional numbering ignores named fields.

Returning Multiple Values

Records remove the need for a throwaway Pair or Result class.

(double min, double max) bounds(List<double> values) {
  var lo = values.first;
  var hi = values.first;
  for (final v in values) {
    if (v < lo) lo = v;
    if (v > hi) hi = v;
  }
  return (lo, hi);
}

void main() {
  final (low, high) = bounds([4.5, 1.2, 9.8, 3.3]);
  print('min=$low max=$high'); // min=1.2 max=9.8
}

The function scans the list once in O(n) and returns two values. The caller destructures the result in one declaration.

Structural Equality

Two records are equal when their shapes and field values match. This holds without you overriding == or hashCode.

void main() {
  print((1, 'a') == (1, 'a'));                   // true
  print((x: 1, y: 2) == (x: 1, y: 2));           // true
  print((1, 2) == (2, 1));                        // false
}

This makes records good Map keys and Set members.

final visited = <(int, int)>{};
visited.add((2, 3));
print(visited.contains((2, 3))); // true

You can alias a record shape with a typedef when it appears in several places:

typedef Coordinates = ({double lat, double lng});

Coordinates london() => (lat: 51.5074, lng: -0.1278);

Records vs. Classes vs. Maps

Criterion Record Class Map<String, dynamic>
Type safety Full, per-field types Full None (dynamic)
Boilerplate Minimal High (ctor, ==, hashCode) Minimal
Equality Structural, automatic Manual override Reference-based
Methods/behavior None Yes None
Mutability Immutable Configurable Mutable
Best for Temporary grouping, multi-return Domain models with logic Raw JSON before validation

Use records for short-lived data. Use a class when the data needs behavior, inheritance, or a name that carries domain meaning.

Pattern Matching in Dart 3

A pattern tests a value’s shape and, on a match, binds parts of it to variables. Patterns appear in switch statements, switch expressions, if-case conditions, and variable declarations.

Switch Expressions

A switch expression returns a value. It uses => instead of case ... : and break.

String fizzBuzz(int n) => switch ((n % 3, n % 5)) {
      (0, 0) => 'FizzBuzz',
      (0, _) => 'Fizz',
      (_, 0) => 'Buzz',
      _ => '$n',
    };

void main() {
  print(fizzBuzz(15)); // FizzBuzz
  print(fizzBuzz(9));  // Fizz
  print(fizzBuzz(7));  // 7
}

The switch matches on a record. The wildcard _ matches anything. Cases run top to bottom and the first match wins.

Guard Clauses with when

Add a when clause to refine a match with a boolean condition.

String classify(int n) => switch (n) {
      < 0 => 'negative',
      0 => 'zero',
      int v when v.isEven => 'positive even',
      _ => 'positive odd',
    };

< 0 is a relational pattern. The when guard runs only after the pattern itself matches.

Destructuring Lists and Maps

void main() {
  // List pattern
  final [first, ..., last] = [10, 20, 30, 40];
  print('$first $last'); // 10 40

  // Map pattern
  final {'host': host, 'port': port} = {'host': 'localhost', 'port': 8080};
  print('$host:$port');  // localhost:8080
}

A list pattern checks length and shape. The ... rest element matches any number of elements. A map pattern requires the listed keys to exist, otherwise the match fails (and an unconditional declaration like the one above throws).

Validating JSON with if-case

This is where patterns and null safety meet. if-case checks structure and types, then binds variables, all in one condition.

void handle(Object? json) {
  if (json case {'name': String name, 'age': int age} when age >= 18) {
    print('Adult user: $name ($age)');
  } else {
    print('Invalid or underage payload');
  }
}

void main() {
  handle({'name': 'Ada', 'age': 36});   // Adult user: Ada (36)
  handle({'name': 'Bob', 'age': '12'}); // Invalid or underage payload
  handle(null);                          // Invalid or underage payload
}

The second call fails because '12' is a String, not an int. The third fails because null is not a map. No manual is checks and no casts.

Null-Handling Patterns

Two pattern forms deal with nullability directly:

void inspect(String? value) {
  switch (value) {
    case String s?:       // Null-check pattern: matches non-null, binds s
      print('Got ${s.length} chars');
    case null:
      print('Nothing here');
  }
}

void main() {
  inspect('Dart'); // Got 4 chars
  inspect(null);   // Nothing here
}

The null-check pattern (pattern?) matches only non-null values. The null-assert pattern (pattern!) throws if the value is null, so treat it with the same suspicion as the ! operator.

Sealed Classes and Exhaustiveness

A sealed class declares a closed set of subtypes. The compiler then verifies that your switch covers every one of them.

import 'dart:math' show pi;

sealed class Shape {}

final class Circle extends Shape {
  final double radius;
  Circle(this.radius);
}

final class Rectangle extends Shape {
  final double width, height;
  Rectangle(this.width, this.height);
}

double area(Shape shape) => switch (shape) {
      Circle(radius: final r) => pi * r * r,
      Rectangle(width: final w, height: final h) => w * h,
    };

void main() {
  print(area(Circle(2)).toStringAsFixed(2)); // 12.57
  print(area(Rectangle(3, 4)));              // 12.0
}

The switch uses object patterns to read each subtype’s fields. If you later add a Triangle subclass, area stops compiling until you handle it. That turns a forgotten branch into a build error instead of a production bug.

Combining All Three: A Result Type

This example uses a sealed hierarchy, null-safe fields, records, and pattern matching together.

sealed class Result<T> {}

final class Ok<T> extends Result<T> {
  final T value;
  Ok(this.value);
}

final class Err<T> extends Result<T> {
  final String message;
  Err(this.message);
}

/// Parses "host:port" into a record, or returns an error.
Result<({String host, int port})> parseEndpoint(String? raw) {
  if (raw == null || raw.isEmpty) return Err('Endpoint is empty');

  final parts = raw.split(':');
  if (parts case [final host, final portText]) {
    final port = int.tryParse(portText);
    if (port == null) return Err('Port is not numeric');
    return Ok((host: host, port: port));
  }
  return Err('Expected host:port');
}

void main() {
  for (final input in ['localhost:8080', 'localhost', null, 'api:abc']) {
    final message = switch (parseEndpoint(input)) {
      Ok(value: (host: final h, port: final p)) => 'Connected to $h on $p',
      Err(message: final m) => 'Error: $m',
    };
    print(message);
  }
}

Output:

Connected to localhost on 8080
Error: Expected host:port
Error: Endpoint is empty
Error: Port is not numeric

The nullable raw is handled at the top. A list pattern validates the split result. A record carries the parsed values. A sealed type forces the caller to handle both outcomes.

Edge Cases and Performance Notes

  • Order matters. The compiler flags a case as unreachable if an earlier pattern already covers it. Put specific patterns before general ones.
  • Map patterns ignore extra keys. {'a': var x} matches {'a': 1, 'b': 2}. List patterns do not ignore extra elements unless you use ....
  • Records with different field names are different types. (x: 1) and (y: 1) are not interchangeable.
  • Records are shallowly immutable. A record holding a List still lets you mutate that list.
  • Exhaustiveness applies to sealed types, enums, bool, and records of those. An int switch needs a default or wildcard case.
  • Bang operators hide bugs. value! compiles cleanly and fails at runtime. Prefer promotion or a null-check pattern.
  • Switch dispatch cost is small. A switch compiles to type and value tests, comparable to a hand-written if/else if chain. Choose patterns for correctness and readability, not speed.

Best Practices: Bad Code vs. Good Code

Anti-Pattern 1: Bang Operator Overuse

// Bad: crashes if 'email' is missing or not a String
String getEmail(Map<String, dynamic> json) {
  return json['email']!.toString().toLowerCase();
}
// Good: validates shape and type, handles failure explicitly
String? getEmail(Map<String, dynamic> json) {
  if (json case {'email': String email}) return email.toLowerCase();
  return null;
}

Anti-Pattern 2: Manual Type Checks and Casts

// Bad: repeated is-checks and casts
String describe(Object obj) {
  if (obj is int) {
    return obj > 0 ? 'positive int' : 'non-positive int';
  } else if (obj is String) {
    return 'string of ${obj.length}';
  } else if (obj is List && obj.length == 2) {
    return 'pair: ${obj[0]}, ${obj[1]}';
  }
  return 'unknown';
}
// Good: one switch, no casts, each branch binds its own variables
String describe(Object obj) => switch (obj) {
      int n when n > 0 => 'positive int',
      int _ => 'non-positive int',
      String s => 'string of ${s.length}',
      [var a, var b] => 'pair: $a, $b',
      _ => 'unknown',
    };

Anti-Pattern 3: Single-Use Wrapper Classes

// Bad: a class created only to return two values
class MinMax {
  final int min;
  final int max;
  MinMax(this.min, this.max);
}
// Good: a record with named fields
({int min, int max}) minMax(List<int> xs) =>
    (min: xs.reduce((a, b) => a < b ? a : b),
     max: xs.reduce((a, b) => a > b ? a : b));

Frequently Asked Questions

What is sound null safety in Dart?

Sound null safety means the type system guarantees that a non-nullable variable never holds null. The compiler enforces this statically, and the guarantee also lets the compiler generate more optimized code. You opt into nullability explicitly with ?, such as int?.

What is the difference between a Dart record and a class?

A record is an anonymous, immutable value type defined by its shape, with built-in structural equality. A class is a named type that can carry methods, inheritance, and mutable state. Use records for temporary grouping and multiple return values. Use classes for domain models with behavior.

How do you use pattern matching in a Dart switch statement?

Write a pattern after case (or before => in a switch expression) to test a value’s type and shape. The pattern can bind variables and take a when guard. For example, Circle(radius: final r) => pi * r * r matches a Circle and binds its radius to r.

What does exhaustiveness checking do in Dart 3?

Exhaustiveness checking verifies that a switch handles every possible value of its input type. It works with sealed classes, enums, bool, and records of those types. A missing case is a compile-time error, so adding a subtype forces you to update every switch that uses it.

Hot this week

Memory Management Across Languages: C++, Java, Python, and JavaScript

Compare manual allocation, garbage collection, and reference counting in C++, Java, Python, and JavaScript. See code and fix leaks today.

JavaScript Operators, Type Coercion, and == vs ===

Master JavaScript operators, type coercion rules, and == vs === with code examples, comparison tables, and fixes. Write safer comparisons today.

Common Python Beginner Mistakes (and How to Avoid Them)

Avoid the 10 most common Python beginner mistakes, from mutable defaults to bare except. Learn the fixes with code examples and start coding cleaner.

Your First Java Program: Hello World With Modern Java

Write your first Java Hello World in Java 25. Compare classic and compact versions, run code with one command, and fix common errors. Start coding now.

std::print and std::format: Modern C++ Output

Learn std::print and std::format in C++23: syntax, format specs, custom formatters, and migration from printf and iostream. Copy the examples now.

Topics

Memory Management Across Languages: C++, Java, Python, and JavaScript

Compare manual allocation, garbage collection, and reference counting in C++, Java, Python, and JavaScript. See code and fix leaks today.

JavaScript Operators, Type Coercion, and == vs ===

Master JavaScript operators, type coercion rules, and == vs === with code examples, comparison tables, and fixes. Write safer comparisons today.

Common Python Beginner Mistakes (and How to Avoid Them)

Avoid the 10 most common Python beginner mistakes, from mutable defaults to bare except. Learn the fixes with code examples and start coding cleaner.

Your First Java Program: Hello World With Modern Java

Write your first Java Hello World in Java 25. Compare classic and compact versions, run code with one command, and fix common errors. Start coding now.

std::print and std::format: Modern C++ Output

Learn std::print and std::format in C++23: syntax, format specs, custom formatters, and migration from printf and iostream. Copy the examples now.

Value Types vs Reference Types in C#: A Visual Guide

Learn how C# value types and reference types differ in memory, copying, and equality. Stack vs heap diagrams and code examples. Read the guide.

JavaScript Data Types: Primitives, Objects, and typeof

Learn all 8 JavaScript data types, how primitives differ from objects, and how typeof works, with code examples. Read the full guide now.

Variables in JavaScript: let, const, and Why var Is Legacy

Learn how let, const, and var differ in JavaScript: scope, hoisting, and the TDZ. See why var is legacy and refactor your code today.

Related Articles

Popular Categories