Structs, tuples, and records

suggest change

Dart has no struct keyword and no separate tuple type. Since Dart 3.0 it has records, which cover both:

Records are immutable, have value equality and need no declaration. When you need a named type with methods, validation or mutable fields, you write a class instead. This article covers records in depth, then shows how to write struct-like classes and when to pick which. For taking records apart see Destructuring, and for matching them in switch see Pattern matching. The examples were run with Dart 3.13.

Creating records

A record literal is a comma-separated list of fields in parentheses. Positional fields are read with $1, $2, ..., named fields with their name:

void main() {
  // Positional fields: a tuple.
  final pair = ('Alice', 42);
  print(pair);
  print(pair.$1);
  print(pair.$2);

  // Named fields: an anonymous struct.
  final point = (x: 3, y: 4);
  print(point);
  print(point.x + point.y);

  // Both kinds in one record.
  final entry = ('id-7', 3.5, active: true);
  print(entry.$1);
  print(entry.$2);
  print(entry.active);

  // A one-field record needs a trailing comma, otherwise it's just parentheses.
  final one = (42,);
  final notARecord = (42);
  print(one);
  print(notARecord);

  // The empty record.
  const empty = ();
  print(empty);
}

Output:

(Alice, 42)
Alice
42
(x: 3, y: 4)
7
id-7
3.5
true
(42)
42
()

Things to note:

Record types

A record type looks like a record literal with types instead of values. Positional fields are written (String, int) and named fields go in braces: ({double min, double max}). Use them as return types to return several values from a function:

(String, int) nameAndAge() => ('Bob', 30);

({double min, double max}) bounds(List<double> xs) {
  var min = xs.first, max = xs.first;
  for (final x in xs) {
    if (x < min) min = x;
    if (x > max) max = x;
  }
  return (min: min, max: max);
}

void main() {
  final (String, int) p = nameAndAge();
  print('${p.$1} is ${p.$2}');

  final b = bounds([3.5, -1, 8, 2]);
  print('min=${b.min} max=${b.max}');

  // Named fields can be written in any order; the type is the same.
  ({int a, String b}) r = (b: 'x', a: 1);
  print(r);
  print(r.runtimeType);
  print(p.runtimeType);
}

Output:

Bob is 30
min=-1.0 max=8.0
(a: 1, b: x)
({int a, String b})
(String, int)

A record type is defined by its shape: the number of positional fields, the set of named field names, and the field types. Two records with the same shape have the same type, no matter where they were created. Named fields are unordered, so (b: 'x', a: 1) and (a: 1, b: 'x') are the same record. toString prints them sorted by name.

Usually you'd destructure the result right away instead of using $1 and b.min. See Destructuring for final (name, age) = nameAndAge(); and final (:min, :max) = bounds(xs);.

Naming record types with typedef

Spelling out ({int x, int y}) everywhere gets noisy. A typedef gives the shape a name:

typedef Point = ({int x, int y});
typedef Range = (int start, int end);

Point move(Point p, int dx, int dy) => (x: p.x + dx, y: p.y + dy);

int length(Range r) => r.$2 - r.$1;

void main() {
  const Point origin = (x: 0, y: 0);
  final p = move(origin, 2, 5);
  print(p);

  // The names in a positional record type are documentation only.
  final Range r = (10, 25);
  print(length(r));
  (int, int) plain = r; // same type as Range
  print(plain);

  // A typedef is an alias, not a new type.
  ({int x, int y}) q = p;
  print(q == p);
}

Output:

(x: 2, y: 5)
15
(10, 25)
true

In (int start, int end) the names start and end don't create getters; you still use $1 and $2. If you want to access fields by name, make them named fields.

A typedef is only an alias. Any ({int x, int y}) is a Point, including one that means "width and height". If you need the type system to keep two shapes apart, use a class or an extension type (see below).

Equality and hashing

Records compare by value: two records are equal if they have the same shape and their corresponding fields are ==. hashCode is consistent with that, so records work as map keys and set elements without any extra code:

void main() {
  final a = (1, 'one', flag: true);
  final b = (1, 'one', flag: true);
  print(a == b);
  print(identical(a, b));
  print(a.hashCode == b.hashCode);

  print((1, 2) == (2, 1));
  print((x: 1, y: 2) == (y: 2, x: 1)); // order of named fields doesn't matter
  print((1, 2) == (x: 1, y: 2)); // different shape

  // Records work as map keys and set elements.
  final grid = <(int, int), String>{
    (0, 0): 'start',
    (2, 3): 'treasure',
  };
  print(grid[(2, 3)]);
  print(grid.containsKey((1, 1)));

  final seen = {(1, 2), (3, 4), (1, 2)};
  print(seen);
}

Output:

true
false
true
false
true
false
treasure
false
{(1, 2), (3, 4)}

Don't rely on identical for records. The language allows the compiler to copy, merge or unbox records, so identity is unspecified; always compare with ==.

Record equality is shallow: each field is compared with its own ==. A record holding two different but equal-looking lists is not equal to the other, because lists compare by identity. Values and references shows this in detail.

Records are immutable

Records have no setters. To "change" a field, build a new record:

void main() {
  var p = (x: 1, y: 2);
  // p.x = 10; // error: there isn't a setter named 'x'

  // "Change" a field by building a new record.
  p = (x: 10, y: p.y);
  print(p);

  // A variable holding a record can be reassigned; the record itself can't change.
  final list = [1, 2];
  final r = (name: 'nums', items: list);
  list.add(3);
  print(r);
}

Output:

(x: 10, y: 2)
(items: [1, 2, 3], name: nums)

The record r is immutable, but its items field is a reference to a mutable list, so changes to the list show through. A record is a true value only if all its fields are immutable.

Adding methods with extensions

Records can't declare methods, but you can add them with an extension on the record type. Combined with a typedef, this gets you most of what a small struct with methods would give you, including a copyWith:

import 'dart:math';

typedef Vec = ({double x, double y});

extension VecOps on Vec {
  double get length => sqrt(x * x + y * y);
  Vec operator +(Vec o) => (x: x + o.x, y: y + o.y);
  Vec scale(double k) => (x: x * k, y: y * k);
  Vec copyWith({double? x, double? y}) => (x: x ?? this.x, y: y ?? this.y);
}

void main() {
  final Vec v = (x: 3.0, y: 4.0);
  print(v.length);
  print(v + (x: 1.0, y: 1.0));
  print(v.scale(2));
  print(v.copyWith(y: 0));
}

Output:

5.0
(x: 4.0, y: 5.0)
(x: 6.0, y: 8.0)
(x: 3.0, y: 0.0)

The extension applies to every record of type ({double x, double y}), not only those you think of as vectors. Extension methods are resolved statically, so they don't work through dynamic or Object. See Extension methods.

Type tests and matching

You can test a value against a record type with is, and match records in switch. Record types are covariant: (int, String) is a subtype of (num, Object). The Record class is the supertype of all records:

String describe(Object o) => switch (o) {
      (int _, int _) => 'pair of ints',
      (String _, _) => 'pair starting with a String',
      (num x, num y) when x == y => 'two equal numbers',
      (x: int _, y: int _) => 'named point',
      Record() => 'some other record',
      _ => 'not a record',
    };

void main() {
  for (final o in [(1, 2), ('a', false), (1.5, 1.5), (x: 1, y: 2), (1, 2, 3), [1, 2]]) {
    print('$o: ${describe(o)}');
  }

  // is-checks work with record types.
  Object r = (1, 'text');
  print(r is (int, String));
  print(r is (num, Object)); // record types are covariant in field types
  print(r is (int, int));
}

Output:

(1, 2): pair of ints
(a, false): pair starting with a String
(1.5, 1.5): two equal numbers
(x: 1, y: 2): named point
(1, 2, 3): some other record
[1, 2]: not a record
true
true
false

A common mistake is writing case (int, int):. Inside a pattern, a bare int is a constant pattern that compares the field to the Type object int, so it never matches a pair of numbers:

void main() {
  Object o = (1, 2);
  switch (o) {
    case (int, int):
      print('matched (int, int)');
    default:
      print('no match');
  }
}

Output:

no match

dart analyze with the default settings reports no issues here. Write (int _, int _) or bind the fields with (int a, int b). The type_literal_in_constant_pattern lint (in package:lints/core.yaml, so also in recommended.yaml) flags the mistake.

Records in collections

Lists of records are a lightweight replacement for a list of small objects. indexed on any Iterable produces (int, E) records, and a for loop can destructure each element:

void main() {
  final scores = [
    (name: 'Carol', score: 88),
    (name: 'Alice', score: 95),
    (name: 'Bob', score: 88),
  ];

  // Sort by score descending, then by name.
  scores.sort((a, b) {
    final c = b.score.compareTo(a.score);
    return c != 0 ? c : a.name.compareTo(b.name);
  });
  for (final (:name, :score) in scores) {
    print('$name $score');
  }

  // indexed gives (int, E) records.
  for (final (i, s) in scores.indexed) {
    print('${i + 1}. ${s.name}');
  }

  // Group by a computed key.
  final byScore = <int, List<String>>{};
  for (final s in scores) {
    (byScore[s.score] ??= []).add(s.name);
  }
  print(byScore);
}

Output:

Alice 95
Bob 88
Carol 88
1. Alice
2. Bob
3. Carol
{95: [Alice], 88: [Bob, Carol]}

The element type is inferred as ({String name, int score}), so a.score and s.name are checked by the compiler. See Sorting for more on comparators.

Awaiting several futures

dart:async adds a wait getter to records of futures (for 2 to 9 fields). Unlike Future.wait, which returns List<Object> for futures of different types, each result keeps its own type:

Future<String> fetchUser() async {
  await Future.delayed(const Duration(milliseconds: 20));
  return 'alice';
}

Future<int> fetchCount() async {
  await Future.delayed(const Duration(milliseconds: 10));
  return 17;
}

Future<void> main() async {
  // .wait on a record of futures keeps each result's type.
  final (user, count) = await (fetchUser(), fetchCount()).wait;
  print('$user has $count items');
  print(user.toUpperCase()); // user is a String, not Object
}

Output:

alice has 17 items
ALICE

Both futures run concurrently. If any of them fails, wait throws a ParallelWaitError that holds both the values and the errors.

Records and JSON

jsonEncode doesn't know about records, so you convert them to and from maps yourself. A map pattern makes the decoding side short and type-safe:

import 'dart:convert';

typedef User = ({String name, int age, List<String> roles});

Map<String, Object?> userToJson(User u) =>
    {'name': u.name, 'age': u.age, 'roles': u.roles};

User userFromJson(Map<String, Object?> json) {
  if (json case {
        'name': String name,
        'age': int age,
        'roles': List<Object?> roles,
      }) {
    return (name: name, age: age, roles: roles.cast<String>());
  }
  throw FormatException('invalid user: $json');
}

void main() {
  final User u = (name: 'Ann', age: 31, roles: ['admin']);
  final text = jsonEncode(userToJson(u));
  print(text);
  final back = userFromJson(jsonDecode(text) as Map<String, Object?>);
  print(back);

  try {
    jsonEncode(u);
  } on JsonUnsupportedObjectError catch (e) {
    print('jsonEncode(record) throws ${e.runtimeType}');
  }
}

Output:

{"name":"Ann","age":31,"roles":["admin"]}
(age: 31, name: Ann, roles: [admin])
jsonEncode(record) throws JsonUnsupportedObjectError

Code generators such as json_serializable work with classes, not records. If a type crosses an API boundary, a class is usually the better choice. See JSON.

Struct-like classes

When you want a named type, a class with fields is Dart's struct. The simplest version has public mutable fields and nothing else:

// A plain mutable struct: public fields, no behavior.
class Rect {
  int x, y, width, height;
  Rect(this.x, this.y, this.width, this.height);
}

void main() {
  final a = Rect(0, 0, 10, 5);
  final b = a; // copies the reference, not the fields
  b.width = 99;
  print(a.width);

  print(Rect(1, 2, 3, 4) == Rect(1, 2, 3, 4)); // identity, not field-by-field
  print(a);
}

Output:

99
false
Instance of 'Rect'

Unlike C# or Swift structs, a Dart class instance is never copied on assignment. b = a makes both variables refer to the same object, so changing b.width changes a.width. A class also compares by identity and has a useless default toString until you override them. See Values and references.

Immutable value classes

To get struct-like value semantics from a class, make every field final, add a const constructor and override ==, hashCode and toString. A copyWith method replaces field assignment:

// An immutable value class: the closest thing to a struct with value semantics.
final class Money {
  final int cents;
  final String currency;

  const Money(this.cents, this.currency);

  Money copyWith({int? cents, String? currency}) =>
      Money(cents ?? this.cents, currency ?? this.currency);

  Money operator +(Money other) {
    if (other.currency != currency) {
      throw ArgumentError('currency mismatch: $currency vs ${other.currency}');
    }
    return Money(cents + other.cents, currency);
  }

  @override
  bool operator ==(Object other) =>
      other is Money && other.cents == cents && other.currency == currency;

  @override
  int get hashCode => Object.hash(cents, currency);

  @override
  String toString() =>
      'Money(${cents ~/ 100}.${(cents % 100).toString().padLeft(2, '0')} $currency)';
}

void main() {
  const price = Money(1999, 'USD');
  final total = price + const Money(501, 'USD');
  print(total);
  print(total == const Money(2500, 'USD'));
  print({price, const Money(1999, 'USD')}.length);
  print(price.copyWith(currency: 'EUR'));

  // const instances with equal fields are the same object.
  print(identical(const Money(1, 'USD'), const Money(1, 'USD')));

  // Classes can be destructured with object patterns.
  final Money(:cents, :currency) = total;
  print('$cents $currency');
}

Output:

Money(25.00 USD)
true
1
Money(19.99 EUR)
true
2500 USD

This is more code than a record, but in return you get a distinct named type, a place for validation and methods, a custom toString, and something you can document, export and evolve without breaking callers. Use Object.hash (or Object.hashAll for lists) to combine field hashes. Equality and comparison and Immutability cover these overrides in more depth. Packages such as freezed and equatable generate or remove most of this boilerplate.

Extension types: named wrappers at zero cost

A typedef of a record doesn't create a new type, but an extension type does. It's a compile-time wrapper around one value, useful for "newtype" IDs that must not be mixed up:

extension type const UserId(int value) {}
extension type const OrderId(int value) {}

void ship(OrderId order, UserId user) => print('ship order ${order.value} to user ${user.value}');

void main() {
  const user = UserId(7);
  const order = OrderId(1001);
  ship(order, user);
  // ship(user, order); // compile-time error: UserId isn't an OrderId
  print(user == UserId(7));
  print(user); // at run time it's just an int
}

Output:

ship order 1001 to user 7
true
7

At run time a UserId is a plain int, with no allocation or wrapper object, which is also why it prints as 7. The representation can be a record too, as in extension type Point(({int x, int y}) r) {}, if you want a distinct type with record equality.

Choosing between them

Need Use
Return 2-3 values from a function positional record (T1, T2)
Small local grouping, map key made of several values record
Fields that are easier to read by name named record ({T a, T b}), plus a typedef
Methods on a lightweight shape record typedef + extension
Distinct named type, validation, docs, public API immutable class with ==/hashCode
Mutable state that changes over time class with non-final fields
Type-safe wrapper around one value extension type
JSON serialization with code generation class

Records are best for short-lived values that are created and consumed close together: a function result that's destructured on the next line, a composite map key, a switch on several values at once. Once a shape is passed through several layers of code, gets methods, or appears in a public API, promote it to a class.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents