Records
Records are anonymous, immutable, fixed-size aggregates, and value types semantically (structural == and hashCode).
Use them for lightweight grouping (multiple returns, map keys, tuples in streams). Use classes for named domain concepts with behavior.
// Positional record
(int, String) pair = (1, 'one');
print((pair.$1, pair.$2)); // (1, one)
// Named fields
({String name, int age}) person = (name: 'Ana', age: 30);
print(person.name);
// Mixed
var mixed = (1, 'x', flag: true);
print((mixed.$1, mixed.flag));
// Functions returning multiple values
(double min, double max) bounds(List<double> values) {
final sorted = [...values]..sort();
return (sorted.first, sorted.last);
}
void main() {
final (lo, hi) = bounds([3, 1, 9]); // destructuring
print('$lo..$hi');
var (:name, :age) = person; // destructure named fields
print('$name is $age');
// Records are immutable and have structural equality
print((1, 2) == (1, 2)); // true
final map = {(0, 0): 'origin', (1, 2): 'point'};
print(map[(1, 2)]);
// Swap
var a = 1, b = 2;
(a, b) = (b, a);
}
typedef Coordinates = ({double lat, double lng});
Coordinates locate() => (lat: 18.52, lng: 73.85);