CodeBlanks Logo Icon CodeBlanks

Records and patterns

Learn records and patterns design.

Records

Records, introduced in Dart 3, are a lightweight data grouping feature. (int, String) holds an integer and a string together. With final pair = (42, 'Hello'); you store two values in a single variable.

Fields are accessed with .$1 and .$2: pair.$1 returns 42. Named fields are also possible: ({int x, int y}). Records are struct-like but inheritance-free and value-based.

Patterns

Patterns, introduced in Dart 3, are a syntax that deconstructs structures like records, lists, and maps. Pattern matching happens in a switch expression: switch (pair) { case (int x, String y): print('$x $y'); }.

Patterns extract values and provide matching. With destructuring, variable binding and guards (when), powerful flow control is possible. Patterns make code more declarative.

Practice A switch expression with a record pattern

Define a String describePoint(int x, int y) function whose body uses a switch expression: return switch ((x, y)) { (0, 0) => 'Origin', (int a, int b) => '$a,$b' };. In main add print(describePoint(0, 0)); and print(describePoint(3, 4));.

Starter code

main.dart
void main() {
  // define describePoint function (switch + record pattern)
  // print calls for two points
}

Sample solution

main.dart
String describePoint(int x, int y) {
  return switch ((x, y)) {
    (0, 0) => 'Origin',
    (int a, int b) => '$a,$b',
  };
}

void main() {
  print(describePoint(0, 0));
  print(describePoint(3, 4));
}

Expected output

Origin
3,4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Record field access

Question
final pair = (42, 'Hello');
print(pair.____);
Answer
final pair = (42, 'Hello');
print(pair.$1);

Explanation: pair.$1 returns the first field (42).

2 Match the pattern parts

Term Meaning
(int, String) Record type
case (int x, String y) Pattern match
$1 First field access
switch Flow expression

3 When are records useful?

  • To store a single value
  • To group multiple values in a lightweight way Correct answer
  • For inheritance instead of a class
  • To store async operation results

Explanation: records group multiple values in a lightweight, inheritance-free way.

All lessons in Expert