Named Records#
About#
- Field Names make records self-documenting
- Can mix positional and named fields
- Type inference works with named fields
- Better readability than positional records
Main Topics#
-
Basic Syntax
- Definition: Colon-separated name-value pairs
- Example:
var user = (name: 'Alice', age: 30);
-
Type Annotations
- Definition: Explicit named record types
- Example:
({String name, int age}) getUser() { return (name: 'Bob', age: 25); }
-
Accessing Fields
- Definition: Dot notation access
- Example:
var person = getUser(); print(person.name); // 'Bob' print(person.age); // 25
How to Use#
- API Design: Return clearly named data
- Configuration: Group related settings
- Data Transfer: Between function calls
How It Works#
- Type Safety: Field names are part of type
- Memory: Same efficiency as positional
- Patterns: Work with all pattern features
Example:
({double lat, double lng}) getLocation() {
return (lat: 47.6062, lng: -122.3321);
}
void main() {
var location = getLocation();
print('Latitude: ${location.lat}');
}
Conclusion#
Named records bring clarity to data grouping by labeling fields while maintaining all the performance benefits of positional records. They’re particularly valuable when field meanings aren’t obvious from position alone.