Dart Record Destructuring
Record destructuring unpacks a record into separate variables in one declaration. The pattern names each part, so the values are ready to use at once.
Unpacking a returned record
describe returns a record with a number and a word. The declaration pattern unpacks both parts into value and word.
(int, String) describe(int n) {
if (n < 0) {
return (n, 'negative');
}
return (n, 'ok');
}
void main() {
var (value, word) = describe(5);
print('$value $word');
}Swapping two values
a starts at 1 and b starts at 2. The pattern assignment rebuilds the pair in the other order, so the print shows the swapped values.
void main() {
var a = 1;
var b = 2;
(a, b) = (b, a);
print('a $a b $b');
}Named fields with the shorthand
named holds two named fields. The shorthand pattern binds x and y variables with the same names as the fields.
void main() {
var named = (x: 3, y: 4);
var (:x, :y) = named;
print('x $x y $y');
}Destructuring in a for-in loop
pairs holds two records. Each loop step unpacks the current record into n and word before the print runs.
void main() {
var pairs = [(1, 'one'), (2, 'two')];
for (var (n, word) in pairs) {
print('$n $word');
}
}Example
void main() {
var (first, :label) = (9, label: 'nine');
print('$first $label');
var (amount, :unit) = (250, unit: 'metres');
print('$amount $unit');
}Key points
- Destructuring unpacks a record into named variables in one line.
- A positional pattern binds the fields in order, from first to last.
- A named pattern uses the shorthand (:x, :y) to bind variables that share the field names.
- A pattern assignment such as (a, b) = (b, a) swaps two values with no extra variable.
- Destructuring also works in a for-in loop over a list of records.
In this example, each declaration mixes one positional field with one named field. The first pattern binds 9 to first and nine to label, so the first print shows 9 nine. The second pattern binds 250 to amount and metres to unit, so the second print shows 250 metres.
Note
The pattern must match the shape of the record. A pattern with the wrong fields does not compile.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does var (a, b) = (10, 20); do?