Dart Record Types
A record is a fixed collection of values grouped into one value. The values stay together and are read back through their fields.
Positional fields read by number
The record holds 3 and 4 in order. The getters .$1 and .$2 read them back, and the last print adds them.
void main() {
var point = (3, 4);
print(point.$1);
print(point.$2);
print(point.$1 + point.$2);
}Named fields read by name
This record names its fields x and label. Each field is read back through its name.
void main() {
var place = (x: 10, label: 'home');
print(place.x);
print(place.label);
}A typed record in and out of a function
The label function takes an (int, String) record and returns one of the same type. The returned number is the input number plus 10, and the word passes through unchanged.
(int, String) label((int, String) pair) {
return (pair.$1 + 10, pair.$2);
}
void main() {
(int, String) result = label((32, 'dart'));
print(result.$1);
print(result.$2);
}Reading a field the record does not have
The record holds only two values, so it has no third field. Asking for it is a compile error, and the program does not run.
void main() {
var pair = (1, 2);
print(pair.$3);
}Example
void main() {
print((1, 'a') == (1, 'a'));
print((1, 'a') == (2, 'a'));
print((x: 1, label: 'one') == (x: 1, label: 'one'));
}Key points
- A record bundles a fixed set of values into a single value.
- Positional fields are read with the getters .$1, .$2 and so on, in the order the values were written.
- Named fields are written with a name and are read back by that name.
- A record type lists the types of its fields, such as (int, String), and the compiler checks values against it.
- Records compare by value, so two records with the same fields and the same values are equal.
In this example, records are compared with the equality operator. The first pair matches in every field, so the comparison prints true. The second pair differs in its first field, so it prints false, and the named records match fully and print true.
Note
A record has a fixed shape, so it has no getter for a field it does not hold.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
How is the second positional field of a record read?