Thuta Learning
Dart
AdvancedProgrammingBeginner

Records, Patterns & Primary Constructors

DartLesson 1840 min

What you'll walk away with

  • Declare positional and named records and read them with $1 or by field name
  • Destructure with record, list, map and object patterns and write a switch expression with guards (when)
  • Explain what the exhaustiveness check protects you from and what a _ catch-all gives up
  • Compare a primary constructor with a classic one and know the SDK version it needs

Explain it simply

Records and patterns in plain language

A record is a small, immutable bundle of a few values, and you do not have to declare and name a class for it. Writing (3, 4) or (name: 'Mia', age: 31) is enough. It is handy when a function needs to hand back two results.

A pattern is a template that checks whether a value has a certain shape and, if it does, pulls the parts into variables. It is like opening a parcel and asking 'is this a box, and what is inside?'. When the shape does not match, that case is skipped and the next one is tried. A primary constructor is a newer, shorter way to write a class's constructor.

Problem → Why → Solution

The problem: returning two results

You need a function that returns the lowest and highest temperature in a list of readings. A Dart function returns one value, so the first attempt is a List<double> read back as result[0] and result[1]. But nothing in that list says which slot is the lowest or how many elements it has, and if an index drifts the compiler stays silent.

The other way out is to declare a MinMax class for this one function. That is type-safe, but it costs fields, a constructor and a whole file of boilerplate, and tomorrow's function that returns three values needs yet another class.

list_as_result.dart
List<double> rangeOf(List<double> values) {
  var lowest = values.first;
  var highest = values.first;
  for (final v in values) {
    if (v < lowest) lowest = v;
    if (v > highest) highest = v;
  }
  return [lowest, highest]; // which slot is which? the type cannot say
}

void main() {
  final result = rangeOf([21.0, -3.2, 95.5]);
  print(result[1] - result[0]);
  print(result[2]); // compiles, then throws a RangeError at run time
}

A list cannot describe a shape

A list does not record its length or the meaning of its slots in its type, so result[2] compiles and only throws a RangeError at run time. A record's type, (double, double), says there are exactly two fields, so the compiler rejects an out-of-range access before the program runs, and you did not have to write a class.

Core concept: records, patterns, exhaustive switch and primary constructors

A record can hold positional fields, (int, String), named fields, ({String name, int age}), or both. Literals look like (1, 'a') and (name: 'Mia', age: 31). Positional fields are read with $1, $2 (counting from one) and named fields by name. Two records are equal when they have the same shape and equal fields, so (x: 1, y: 2) == (y: 2, x: 1) is true, and because a record is immutable there are no setters.

A pattern checks a value's shape and binds its parts to names. You can use them in variable declarations (final (a, b) = pair;), in assignments (the swap (a, b) = (b, a);), in switch, in if (value case pattern) and in for-in loops. The kinds are constants ('boiler'), relational (> 90), logical (|| and &&), list ([a, ..., b]), map ({'id': var id}), record, object (Point(x: var a)), variables that test a type (int n) and the _ wildcard, and a when guard adds a condition.

A switch expression produces a value, needs no break, and each case has the shape pattern => value. Cases are tried top to bottom and the first match wins, so put specific cases above general ones. When you switch over a sealed class, an enum, a bool or records built from them, the compiler checks exhaustiveness: a missing case is a compile error, not a run-time surprise. A _ makes the switch exhaustive but gives up the warning you would get when a new subtype is added later.

A primary constructor moves the constructor's parameter list into the class header: class Point(final int x, final int y);. A parameter with final or var becomes a field; without it, it is only a plain parameter. The feature needs language version 3.13, and I checked that a plain dart run on 3.13.7 accepts it with no flag. Unlike a record, such a class gets no automatic == or toString.

NeedChoose
A function returns 2-3 values, no behaviourA record
You want ==, hashCode and toString for freeA record
Methods, validation, a named type used in many placesA class (primary constructor trims it)
Shape in, pieces out
  1. A value arrives
  2. The pattern tests its shape
  3. On a match, parts bind to names
  4. The first matching case gives the result

If no case matches, a switch statement over an ordinary type just moves on, while a non-exhaustive switch expression does not even compile.

General pattern

dart
typedef Name = ({Type field, Type other});     // named record type
(Type, Type) pair() => (first, second);       // positional record
final (a, b) = pair();                        // destructure it
Result f(Name v) => switch (v) {
      (field: constant, other: > limit) => value,
      (field: var x, other: _) when x > 0 => value,
      (field: var x, other: var y) => value,
    };
class Name(final Type field);                 // primary constructor

A typedef names the record type, and a switch can mix constant, relational and var patterns with guards. The last case catches everything that remains, which makes the switch exhaustive.

Worked example: classifying sensor readings with records

The typedef gives the named record type its name, Reading. rangeOf returns (lowest, highest) as a record, and describe tests three patterns from top to bottom with a switch expression. The first pattern checks the sensor name with a constant, the second checks the temperature with a relational pattern, and the last case catches everything else.

readings.dart
typedef Reading = ({String sensor, double celsius});

// A record lets one function return two values with no helper class.
(double lowest, double highest) rangeOf(List<Reading> readings) {
  var lowest = readings.first.celsius;
  var highest = lowest;
  for (final r in readings) {
    if (r.celsius < lowest) lowest = r.celsius;
    if (r.celsius > highest) highest = r.celsius;
  }
  return (lowest, highest);
}

// A switch expression with record patterns. The last case matches every
// Reading, so the compiler knows the switch is exhaustive.
String describe(Reading reading) => switch (reading) {
      (sensor: 'boiler', celsius: > 90) => 'boiler is overheating',
      (sensor: var name, celsius: < 0) => '$name is freezing',
      (sensor: var name, celsius: var c) => '$name is at ${c.toStringAsFixed(1)} C',
    };

void main() {
  final readings = <Reading>[
    (sensor: 'boiler', celsius: 95.5),
    (sensor: 'garage', celsius: -3.2),
    (sensor: 'office', celsius: 21.0),
  ];

  for (final reading in readings) {
    print(describe(reading));
  }

  final (lowest, highest) = rangeOf(readings);
  print('range: $lowest to $highest');

  // Records compare by value, field by field.
  print(readings.first == (sensor: 'boiler', celsius: 95.5));

  if (readings.last case (sensor: var name, celsius: var c) when c > 20) {
    print('$name is warm');
  }
}

Code breakdown

  1. Name a record typetypedef Reading = ({String sensor, double celsius});

    The typedef lets you call a named record type Reading. It is not a new class: any record with that shape is a Reading.

  2. Return a recordreturn (lowest, highest);

    Parentheses alone make a record. The names in the return type (double lowest, double highest) are documentation only; to read the values you use $1 or destructure them.

  3. Constant and relational patterns(sensor: 'boiler', celsius: > 90) => 'boiler is overheating',

    A record pattern tests each field on its own: sensor must equal 'boiler' and celsius must exceed 90, and only when both hold is this case chosen.

  4. Bind with var(sensor: var name, celsius: < 0) => '$name is freezing',

    var name copies the sensor field into name so the right-hand expression can use it. This case catches any sensor below zero.

  5. Destructurefinal (lowest, highest) = rangeOf(readings);

    The pattern on the left splits the returned record into two variables. A field count that does not match is a compile error.

  6. Structural equalityprint(readings.first == (sensor: 'boiler', celsius: 95.5));

    Records compare by field values, not by object identity, so a freshly built record with the same fields is equal. An ordinary class needs == overridden by hand to do that.

You should see
boiler is overheating
garage is freezing
office is at 21.0 C
range: -3.2 to 95.5
true
office is warm

Records in depth: positional, named and equality

Names inside a positional type annotation, (int x, int y), are documentation only; reading still uses $1 and $2. Writing (int x, int y) p = (1, 2); print(p.x); fails with "The getter 'x' isn't defined for the type '(int, int)'." (reproduced). If you want to read by name, use named fields such as ({int x, int y}).

record_rules.dart
void main() {
  final pair = (1, 'a');
  final person = (name: 'Mia', age: 31);
  final mixed = (1, x: 2);

  print(pair); // (1, a)
  print(person); // (age: 31, name: Mia)  named fields are printed sorted
  print(mixed); // (1, x: 2)
  print(pair.$1 + person.age);

  print((1, 2) == (1, 2)); // true: same shape, same values
  print((x: 1, y: 2) == (y: 2, x: 1)); // true: order of named fields is irrelevant
  print((1, 2) == (2, 1)); // false: positional order matters

  var a = 1, b = 2;
  (a, b) = (b, a); // swap without a temporary
  print('$a $b');

  Object o = (1, 2);
  print(o is (int, int)); // true
  print(o is (int, String)); // false
}

This prints (1, a), (age: 31, name: Mia), (1, x: 2) and 32, then true, true, false, '2 1', true, false. A record cannot be changed: pair.$1 = 5 fails with "The setter '$1' isn't defined" (reproduced). A field also cannot be named like an Object member such as hashCode or toString.

A tour of patterns: list, map, object, relational and guards

One classify function shows most pattern kinds. Cases are tried from top to bottom, so 0 comes before int n and the guarded int n when n < 0 comes before the unguarded int n. [var first, ..., var last] only matches lists with two or more elements; a single-element list is caught by [var only].

pattern_tour.dart
class Point {
  const Point(this.x, this.y);
  final int x;
  final int y;
}

String classify(Object? value) => switch (value) {
      null => 'nothing',
      0 => 'zero',
      int n when n < 0 => 'negative int $n',
      int n => 'int $n',
      String s when s.isEmpty => 'empty string',
      String s => 'string of ${s.length}',
      [] => 'empty list',
      [var only] => 'one item: $only',
      [var first, ..., var last] => 'list from $first to $last',
      {'id': int id} => 'map with id $id',
      Point(x: 0, y: 0) => 'origin',
      Point(:var x, :var y) => 'point $x,$y',
      (int a, int b) => 'pair sums to ${a + b}',
      _ => 'something else',
    };

String grade(int score) => switch (score) {
      < 0 || > 100 => 'invalid',
      >= 90 => 'A',
      >= 80 => 'B',
      _ => 'C or lower',
    };

void main() {
  final samples = <Object?>[
    null, 0, -4, 7, '', 'hey', [], [1], [1, 2, 3],
    {'id': 5}, const Point(0, 0), const Point(2, 3), (1, 2), 3.5,
  ];
  for (final value in samples) {
    print(classify(value));
  }
  print([grade(95), grade(85), grade(-1), grade(50)]);
}
text
nothing, zero, negative int -4, int 7, empty string, string of 3,
empty list, one item: 1, list from 1 to 3, map with id 5, origin,
point 2,3, pair sums to 3, something else
[A, B, invalid, C or lower]

(The output above is shown comma-joined; the program prints one item per line.) When you switch over a sealed type, the compiler tells you about a missing case: with Shape made of Circle, Rect and Tri, leaving out Tri gives "The type 'Shape' is not exhaustively matched by the switch cases since it doesn't match 'Tri()'." (reproduced). Lesson 20 follows that thread in detail.

Primary constructors: the newer syntax and its version requirement

Check your SDK version

Primary constructors are a newer feature that needs language version 3.13. The code in this lesson was run on Dart 3.13.7, where a plain dart run accepts it with no flag. An older SDK or an older language version in pubspec.yaml will not accept it. The record and pattern parts of this lesson work on older Dart 3 SDKs too.

First, a classic constructor and a primary constructor side by side. A parameter in the class header becomes a field when it carries final. The code also tries optional named parameters, defaults, a const class and calling a superclass; initializer-list work goes in the class body as this : ....

primary_constructors.dart
// Classic constructor.
class OldPoint {
  const OldPoint(this.x, this.y);

  final int x;
  final int y;
}

// Primary constructor: the parameter list moves into the class header.
class const NewPoint(final int x, final int y);

// Optional named parameter with a default; the body adds extra members.
class Money(final int cents, {final String currency = 'USD'}) {
  String get label => '$currency ${(cents / 100).toStringAsFixed(2)}';
}

// Initializer-list work (assert, other fields) goes in a `this :` part.
class Range(final int low, final int high) {
  final int span;

  this : assert(high >= low), span = high - low;
}

class Base(final String id);

class Child(String id, final int extra) extends Base {
  this : super(id);
}

void main() {
  const a = OldPoint(1, 2);
  const b = NewPoint(1, 2);
  print('${a.x},${a.y} ${b.x},${b.y}');
  print(Money(1999).label);
  print(Money(500, currency: 'EUR').label);
  print(Range(3, 10).span);
  final c = Child('c-1', 7);
  print('${c.id} ${c.extra}');
}
text
1,2 1,2
USD 19.99
EUR 5.00
7
c-1 7

dart run does not enable asserts by default (running Range(10, 3) without --enable-asserts prints -7, reproduced), so do not lean on assert for validation. A primary-constructor class gets no == either: Point(1, 2) == Point(1, 2) is false and printing it gives Instance of 'Point', while (1, 2) == (1, 2) is true and prints (1, 2).

You can reproduce the version gate yourself: put // @dart=3.12 at the top of a file with class Point(final int x, final int y); and 3.13.7 says "The 'primary-constructors' language feature is disabled for this library." followed by "Try removing the `@dart=` annotation or setting the language version to 3.13 or higher." Without final, class Point(int x, int y); compiles, but x and y are not fields, so Point(1, 2).x gives "The getter 'x' isn't defined for the type 'Point'."

version_gate.dart
// @dart=3.12
// Error on Dart 3.13.7: The 'primary-constructors' language feature is
// disabled for this library.
class Point(final int x, final int y);

void main() {
  print(Point(1, 2).x);
}

In real projects

Where records and patterns show up in real projects

Records fit anywhere a function hands back several results: a parser returning (value, remainingText), or a Future<(int, String)> carrying a status code and a body. Patterns pay off most when reading loosely typed data such as JSON, because checking the shape and extracting the parts happen in one step.

  • Reading a decoded JSON Map<String, Object?> with if (json case {'user': {'name': String name}}): a wrong shape falls to the else branch instead of throwing a cast exception.
  • Looping over a map with for (final MapEntry(:key, :value) in map.entries) saves repeating an index or entry.key.
  • Turning sealed state (loading, success, error) into UI or log text with a switch expression; when you add a state, the compiler points at every switch you have not updated.
json_pattern.dart
void main() {
  final json = <String, Object?>{
    'user': {'name': 'Mia', 'tags': ['dev', 'dart']},
  };
  if (json case {'user': {'name': String name, 'tags': [_, var second]}}) {
    print('$name, second tag: $second');
  }

  final broken = <String, Object?>{
    'user': {'name': 42},
  };
  if (broken case {'user': {'name': String name}}) {
    print('name is $name');
  } else {
    print('unexpected shape');
  }

  for (final MapEntry(:key, :value) in {'a': 1, 'b': 2}.entries) {
    print('$key=$value');
  }
}

Common mistakes

Common mistakes with records and patterns

Reading a positional field by name

Declaring (int x, int y) p = (3, 4); and writing p.x gives "The getter 'x' isn't defined for the type '(int, int)'." Those x and y are documentation. Use $1, destructure with final (x, y) = p;, or choose named fields, ({int x, int y}).

Using a record where a class belongs

A five-field record passed through many functions will leave you missing validation, methods and a named type later. Once it needs behaviour, or appears in more than one signature, switch to a class (a primary constructor keeps it short).

A destructuring pattern with the wrong number of fields

final (a, b) = (1, 2, 3); fails with "The matched value of type '(int, int, int)' isn't assignable to the required type '(Object?, Object?)'." (reproduced). The compiler checks the shape too, which is a real safeguard: destructure all three fields.

Adding _ to a sealed switch and silencing the compiler

Switching over Shape with cases for Circle and Rect plus _ => 0 is exhaustive. When someone adds a Tri subtype tomorrow, the compiler says nothing and Tri silently gets 0. List every subtype explicitly instead.

Forgetting final on a primary constructor parameter

class Point(int x, int y); compiles, but x and y are plain constructor parameters, not fields, so Point(1, 2).x gives "The getter 'x' isn't defined for the type 'Point'." (reproduced). Add final or var when you want a field.

Best practices

Best practices

  • Use records where a function returns two or three values, and name the type with a typedef so signatures read well.
  • In a switch expression, put specific cases first and put a guarded case above the same pattern without a guard.
  • Do not add _ to a switch over a sealed type if you want the compiler to keep warning you about new subtypes.
  • If you adopt primary constructors, raise the sdk constraint in pubspec.yaml so the whole team has a matching SDK.

Mini challenge

Mini challenge: a command parser

Write a parse function that splits a list of words with list patterns into a (command, args) record, and a describe function that turns that record into text. Both must be switch expressions.

  • typedef Parsed = ({String command, int args}); and parse handles [], [cmd] and [cmd, ...rest] as three cases
  • describe uses record patterns to call out 'none' and 'add' with two or more args
  • A final case catches the rest so the switch is exhaustive
  • Loop over five inputs and print each, then destructure one record at the end
command_parser.dart
// Result of parsing a command line.
typedef Parsed = ({String command, int args});

// TODO 1: switch over `words` using list patterns
Parsed parse(List<String> words) {
  // TODO: [] -> command 'none', no args
  // TODO: [cmd] -> that command, no args
  // TODO: [cmd, ...rest] -> that command, rest.length args
  throw UnimplementedError();
}

// TODO 2: switch over the record with record patterns, most specific first
String describe(Parsed p) {
  // TODO: 'none', 'add' with 2+ args, 'add' with 1 arg, no args, anything else
  throw UnimplementedError();
}

void main() {
  // TODO 3: parse and describe five inputs (empty, one word, add x2, rm x3)
  // TODO 4: destructure one result with final (:command, :args) = ...;
}

Expected: Running it should print: none/0: nothing to do list/0: list with no arguments add/1: adding one item add/2: adding several items rm/3: rm with 3 arguments x 1

Show hint

In a list pattern, [var cmd, ...var rest] gives you the remaining elements in rest. In describe, place (command: 'add', args: >= 2) above (command: 'add', args: 1) and keep (command: var c, args: var n) last. Destructure a record with final (:command, :args) = parse([...]);.

Show solution
command_parser.dart
typedef Parsed = ({String command, int args});

Parsed parse(List<String> words) => switch (words) {
      [] => (command: 'none', args: 0),
      [var cmd] => (command: cmd, args: 0),
      [var cmd, ...var rest] => (command: cmd, args: rest.length),
    };

String describe(Parsed p) => switch (p) {
      (command: 'none', args: _) => 'nothing to do',
      (command: 'add', args: >= 2) => 'adding several items',
      (command: 'add', args: 1) => 'adding one item',
      (command: var c, args: 0) => '$c with no arguments',
      (command: var c, args: var n) => '$c with $n arguments',
    };

void main() {
  final inputs = <List<String>>[
    [],
    ['list'],
    ['add', 'milk'],
    ['add', 'milk', 'eggs'],
    ['rm', 'a', 'b', 'c'],
  ];
  for (final words in inputs) {
    final parsed = parse(words);
    print('${parsed.command}/${parsed.args}: ${describe(parsed)}');
  }
  final (:command, :args) = parse(['x', 'y']);
  print('$command $args');
}

Quick quiz 1 / 3

What does print((x: 1, y: 2) == (y: 2, x: 1)) print?

Quick quiz 2 / 3

Circle, Rect and Tri extend a sealed class Shape. What happens with the switch expression switch (s) { Circle() => 'c', Rect() => 'r' }?

Quick quiz 3 / 3

After declaring class Point(int x, int y);, why does print(Point(1, 2).x) fail?

What to remember

  • A record is a small immutable bundle with positional or named fields that compares by field values; read it with $1 or by name.
  • A pattern checks a value's shape and binds its parts; in a switch expression the first matching case wins and a when guard adds a condition.
  • Switching over a sealed type or enum gets an exhaustiveness check from the compiler, and adding _ gives that protection up.
  • A primary constructor (class Point(final int x, final int y);) needs no flag on Dart 3.13.7, needs language version 3.13, and makes a field only when final or var is present.

Dart primary constructors — Dart

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Records, Patterns & Primary Constructors | Thuta Learning