Record
- Dart course
- Intermediate
- Lesson 72/116
- 5 min
Learn tuples with Dart 3 Records.
Records as tuples
Dart 3 Record type bundles several values into one package. For example (int, String) p = (42, 'Dart'); declares a record. Each item in parentheses is a field.
You can access fields by position: p.$1 gives the first value (42), p.$2 the second (Dart). Indexes start at 1.
Records are immutable. Two records with the same fields and values are equal. So records are ideal for carrying data.
Named fields
Records can have named fields alongside positional ones. Example: ({String name, int age}) p = (name: 'Alex', age: 30);. Here you access p.name and p.age.
Named fields are written inside curly braces and accessed by name. Positional fields are accessed with $ indexes.
A record can hold both: (int, {String label}). This flexibility lets you express data structures clearly.
Practice A positional record
In main declare (int, String) p = (7, 'Dart');. Print p.$1 and p.$2 on separate lines with print.
Starter code
void main() {
// declare an (int, String) record, print both fields
}Sample solution
void main() {
(int, String) p = (7, 'Dart');
print(p.$1);
print(p.$2);
}Expected output
7 Dart
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Accessing a record field
var p = (42, 'Dart');
print(p.____);
var p = (42, 'Dart');
print(p.$1);
Explanation: the first field is accessed with $1.
2 What is true of records?
- They are mutable
- They take only two fields
- They replace classes
- Two equal records are equal Correct answer
Explanation: two records with the same fields and values are equal.
3 Match the record parts
| Term | Meaning |
|---|---|
(42, 'Dart') |
Positional record |
(name: 'Alex', age: 30) |
Named record |
p.$1 |
First positional field |
p.name |
Named field |