TExcelTAD
Home › Dart › Dart Records

Dart Records

A record is an anonymous, immutable, fixed-size bundle of values — like a lightweight tuple with optional names. Records arrived in Dart 3 and solve a very common problem: returning more than one value from a function without inventing a class for it.

Creating records

dart · try it yourself
void main() {
  var point = (3, 4);                        // positional fields
  var user = (name: 'Ngan', age: 27);        // named fields
  var mixed = ('GET', path: '/api', retries: 2);

  print(point);
  print(user);
  print(mixed);

  print(point.$1);       // positional fields: $1, $2, …
  print(point.$2);
  print(user.name);      // named fields by name
  print(mixed.$1);
  print(mixed.retries);
}
(3, 4)
(age: 27, name: Ngan)
(GET, path: /api, retries: 2)
3
4
Ngan
GET
2

Note: Named fields are printed in alphabetical order — their order doesn't matter to the record's type.

Record types

A record's type is written like its literal, using types instead of values:

Literal Type
(3, 4) (int, int)
('a', 1.5, true) (String, double, bool)
(x: 1, y: 2) ({int x, int y})
('id', count: 3) (String, {int count})
(42,) (int,) — a one-field record needs a trailing comma
dart · try it yourself
(int, int) swap((int, int) pair) => (pair.$2, pair.$1);

({double min, double max, double mean}) stats(List<double> xs) {
  final total = xs.reduce((a, b) => a + b);
  return (
    min: xs.reduce((a, b) => a < b ? a : b),
    max: xs.reduce((a, b) => a > b ? a : b),
    mean: total / xs.length,
  );
}

void main() {
  print(swap((1, 2)));

  final s = stats([4.0, 9.5, 1.5, 7.0]);
  print('min ${s.min}, max ${s.max}, mean ${s.mean}');
}
(2, 1)
min 1.5, max 9.5, mean 5.5

Returning multiple values + destructuring

The real power comes from combining records with patterns to unpack them:

dart · try it yourself
(String, int)? parseHeader(String line) {
  final parts = line.split(':');
  if (parts.length != 2) return null;
  final value = int.tryParse(parts[1].trim());
  if (value == null) return null;
  return (parts[0].trim(), value);
}

({int quotient, int remainder}) divide(int a, int b) =>
    (quotient: a ~/ b, remainder: a % b);

void main() {
  final (name, size) = parseHeader('Content-Length: 348')!;
  print('$name = $size');

  final (:quotient, :remainder) = divide(17, 5);
  print('17 = 5 * $quotient + $remainder');

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

  if (parseHeader('garbage') case (var key, var value)) {
    print('$key $value');
  } else {
    print('could not parse');
  }
}
Content-Length = 348
17 = 5 * 3 + 2
a=2 b=1
could not parse

(:quotient, :remainder) is shorthand for (quotient: quotient, remainder: remainder) — it binds variables with the same names as the fields.

Value equality

Records compare structurally: two records are equal if they have the same shape and equal fields. They also have a matching hashCode, so they work as map keys and in sets:

dart · try it yourself
void main() {
  print((1, 'a') == (1, 'a'));
  print((x: 1, y: 2) == (y: 2, x: 1));
  print((1, 2) == (2, 1));

  final seats = <(int row, String col), String>{
    (1, 'A'): 'Hoa',
    (1, 'B'): 'Tien',
  };
  print(seats[(1, 'B')]);
  print(seats.containsKey((2, 'A')));
}
true
true
false
Tien
false

Notice the type (int row, String col): names on positional fields are just documentation and don't affect the type.

Records vs classes

Record Class
Declaration needed No Yes
Equality / hashCode / toString Automatic Write yourself
Methods No Yes
Mutable fields Never Optional
Best for Small, local groupings, multiple return values, map keys Domain models with behaviour and a name

Tip: If a record type shows up in many signatures, give it a name with a typedef — typedef Range = ({int start, int end}); — or promote it to a class once it needs methods.

Test yourself

How do you read the second positional field of a record r?

  1. r[1]
  2. r.$2
  3. r.second
  4. r.2

Is (a: 1, b: 2) == (b: 2, a: 1) true?

  1. Yes — named field order doesn't matter
  2. No — order matters
  3. Compile error
  4. Only if both are const

What does final (:lat, :lng) = getLocation(); do?

  1. Creates a map
  2. Destructures named fields lat and lng into variables of the same names
  3. Declares a record type
  4. Calls lat and lng functions