What are Records?
Records (introduced in Dart 3.0) are anonymous immutable aggregate types. They bundle multiple values together without creating a full class. Think of them as lightweight, typed tuples.
Syntax
// Create a record
(int, String) person = (25, 'Alice');
print(person.$1); // 25 (positional access)
print(person.$2); // Alice
// Record type annotation
(double, double) coordinates = (37.7749, -122.4194);
// Return multiple values from a function
(int, String) getUser() => (1, 'Bob');
Named Fields
// Named field records
({String name, int age, String email}) user = (
name: 'Alice',
age: 30,
email: 'alice@example.com'
);
print(user.name); // Alice
print(user.age); // 30
print(user.email); // alice@example.com
// Mix of positional and named
(int, {String name, bool isAdmin}) adminUser = (1, name: 'Bob', isAdmin: true);
print(adminUser.$1); // 1
print(adminUser.name); // Bob
print(adminUser.isAdmin); // true
Destructuring Records
var (x, y) = (10, 20);
print('x=$x, y=$y'); // x=10, y=20
var (:name, :age) = (name: 'Alice', age: 30);
print('$name is $age'); // Alice is 30
// In a for loop
List<(String, int)> scores = [('Alice', 95), ('Bob', 87), ('Charlie', 92)];
for (var (name, score) in scores) {
print('$name: $score');
}
Example: Multi-value Returns
({double min, double max, double average}) stats(List<double> numbers) {
if (numbers.isEmpty) return (min: 0, max: 0, average: 0);
var sorted = [...numbers]..sort();
var sum = numbers.reduce((a, b) => a + b);
return (
min: sorted.first,
max: sorted.last,
average: sum / numbers.length,
);
}
void main() {
var result = stats([5.0, 3.0, 8.0, 1.0, 9.0]);
print('Min: $${result.min}'); // Min: 1.0
print('Max: $${result.max}'); // Max: 9.0
print('Avg: $${result.average}'); // Avg: 5.2
}
Output:Min: 1.0
Max: 9.0
Avg: 5.2
🧠 Quiz
1. How do you access a positional field in a record?
- A) record.first, record.second
- B) record[0], record[1]
- C) record.$1, record.$2 ✅
- D) record.get(0)
2. Are records mutable in Dart?
- A) Yes
- B) No — records are immutable ✅
- C) Only positional fields are mutable
- D) Only named fields are mutable
Summary
Records are anonymous immutable value types introduced in Dart 3.0. Use (Type1, Type2) for positional fields (accessed via .$1, .$2) and ({FieldType name}) for named fields. Records are great for returning multiple values from functions without creating a class.