Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 61 ยท Types and Operators

Records

Learn Dart 3 records: positional and named fields, returning several values from a function, record types, structural equality and destructuring.

Functions return one value. When you need to return two or three related values, such as a minimum and a maximum, or a result and a status, older Dart code reached for a List, a Map or a tiny class. All of those work, but each loses something: a list forgets the types of its elements, a map forgets the keys' meaning, and a class takes several lines to declare.

Records, added in Dart 3, fix this. A record is a fixed-size, immutable group of values, written with parentheses, and the compiler knows the type of every field. You can create one anywhere, pass it around, compare it by value and take it apart again with destructuring. This lesson covers everything you need. Dart code is read-only; the stand-ins use TypeScript tuples and objects, which are close cousins.

Creating records

A record expression is a comma-separated list of values in parentheses:

DART
void main() {
  var pair = (3, 'apples');
  print(pair.$1);     // 3
  print(pair.$2);     // apples
  print(pair);        // (3, apples)
}
TEXT
3
apples
(3, apples)

These are positional fields. You read them with the getters $1, $2, $3 and so on. Notice the numbering starts at one. The record pair has the type (int, String); the type is written like the value, with types instead of expressions.

Fields can also have names. Named fields go in a block after the positional ones, written with a name: value pair:

DART
void main() {
  var person = (name: 'Ada', age: 36);
  print(person.name);   // Ada
  print(person.age);    // 36

  var mixed = (42, label: 'answer');
  print(mixed.$1);      // 42
  print(mixed.label);   // answer
}

In a record type, the named fields are put in braces: ({String name, int age}) for the first, and (int, {String label}) for the second. A record may mix both kinds, but the positional ones are numbered separately from the named ones.

Two details are easy to trip over. A record with exactly one positional field needs a trailing comma, (42,), because plain (42) is just a parenthesized number. And the empty record () is allowed, though rarely useful.

flowchart LR
    R["Record (name: 'Ada', age: 36)"] --> N1["name<br/>String"]
    R --> N2["age<br/>int"]
    P["Record (3, 'apples')"] --> P1["$1<br/>int"]
    P --> P2["$2<br/>String"]

Named fields are accessed by name, positional fields by $1, $2, ... Each has its own static type.

Returning several values

The most common use of a record is to return more than one value from a function without inventing a class:

DART
(int min, int max) minMax(List<int> numbers) {
  var low = numbers.first;
  var high = numbers.first;
  for (var n in numbers) {
    if (n < low) low = n;
    if (n > high) high = n;
  }
  return (low, high);
}

void main() {
  var result = minMax([4, 9, 1, 7]);
  print('min ${result.$1}, max ${result.$2}');   // min 1, max 9
}

The names min and max in the return type (int min, int max) are documentation only: they do not create fields. If you want to read result.min, declare the fields as named: ({int min, int max}) minMax(...) and return (min: low, max: high).

TypeScript Returning two values (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Destructuring

Reaching into a record with $1 is fine, but it is clearer to unpack it into variables. A pattern on the left side of a declaration does exactly that:

DART
void main() {
  var (low, high) = minMax([4, 9, 1, 7]);
  print('$low to $high');            // 1 to 9

  var person = (name: 'Ada', age: 36);
  var (:name, :age) = person;        // :name means name: name
  print('$name is $age');            // Ada is 36

  var (x, y) = (10, 20);
  (x, y) = (y, x);                   // swap without a temp variable
  print('$x $y');                    // 20 10
}

For named fields, :name is shorthand for name: name, which binds a new variable called name from the field called name. You can also rename: var (name: who) = person;. Destructuring in assignments, as in the swap, is also allowed. Patterns have a lesson of their own later in this tutorial; for now just remember that var (a, b) = record; unpacks positional fields and var (:a, :b) = record; unpacks named ones.

Record types and aliases

A record type can appear anywhere a type can: parameters, fields, generics.

DART
typedef Point = (double x, double y);          // positional, names are documentation
typedef User = ({String name, int age});       // named fields

double squaredDistance(Point a, Point b) {
  var dx = a.$1 - b.$1;
  var dy = a.$2 - b.$2;
  return dx * dx + dy * dy;
}

List<(String, int)> scores = [('Ada', 91), ('Alan', 84)];

A typedef gives a record type a short name, which is especially helpful for long ones. The type system treats record types structurally: two record types are the same if their shapes match, so you do not need to declare anything for two parts of a program to agree on (int, String). Named field order does not matter: ({int a, int b}) and ({int b, int a}) are the same type.

Equality is by value

Two records are equal when they have the same shape and equal fields. This is different from most objects, where == compares identity.

DART
void main() {
  print((1, 'a') == (1, 'a'));                          // true
  print((1, 'a') == (1, 'b'));                          // false
  print((name: 'Ada', age: 36) == (age: 36, name: 'Ada'));  // true, order of named fields is ignored
}

Records also get a matching hashCode, so they work well as Map keys and Set members: visited.add((row, col)) is a neat way to track grid positions.

TypeScript has no value equality for tuples, so the stand-in below needs a helper to show the idea.

TypeScript Value equality and map keys (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Records, classes and when to choose

Records are immutable: you cannot assign to a field, you can only create a new record. Records cannot declare methods, and they cannot extend or implement anything. That is the line between records and classes:

  • Use a record for a short-lived bundle of values: a return value, a map key, a quick pair in a list.
  • Use a class when the data has a name and behavior of its own, needs validation, or will be passed through many layers of your program. Named concepts like Money or User deserve a class.

A record can contain mutable objects. (items: <int>[]) is immutable as a record, but the list inside it can still change.

Field names have a few restrictions: they cannot start with an underscore, and they cannot be the names hashCode, runtimeType, toString or noSuchMethod, nor look like positional getters ($1) for a different position.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you read the second positional field of var pair = (3, 'apples');?

    Positional record fields are read with the getters $1, $2, and so on, starting at one.
  2. 2. What is the type of (name: 'Ada', age: 36)?

    Named fields appear in braces inside the record type, and each field keeps its own static type.
  3. 3. What does (1, 'a') == (1, 'a') evaluate to?

    Records have structural equality. Same shape and equal fields means equal records.
  4. 4. Which line unpacks both named fields of person into variables?

    For named fields, the pattern uses :name and :age, shorthand for name: name and age: age.
  5. 5. Which statement about records is true?

    Records are immutable and have no custom methods. A single positional field needs a trailing comma, and named-field order does not affect equality.

Summary

  • A record is an immutable, fixed-size group of values: (1, 'a') or (name: 'Ada', age: 36).
  • Positional fields are read with $1, $2, ... and named fields by name; the record type lists each field's type.
  • Records are ideal for returning several values and for compound map keys.
  • Equality and hashCode are structural, and the order of named fields does not matter.
  • Destructure with var (a, b) = r; or var (:name, :age) = r;.
  • Use a class when the data needs a name, behavior or validation.

Next, put values to work in if, else and Conditional Expressions.