What are Records in Dart 3 and how do they replace custom value classes?
TL;DR: Records are anonymous, immutable value types: (String, int) or (name: String, age: int). They have structural equality built-in, can be destructured, and work with pattern matching. Great for returning multiple values without defining a full class.
Full Answer
Before Dart 3, returning multiple values required a custom class or a List/Map (losing type safety). Records solve this elegantly.
Positional vs Named Fields
Positional: (String, int) โ accessed with .$1, .$2. Named: (name: String, age: int) โ accessed with .name, .age. Mix both: (String, age: int).
Structural Equality
Two records with the same shape and values are equal without overriding == or hashCode. ('Alice', 30) == ('Alice', 30) is true.
Records pair naturally with pattern matching and destructuring in Dart 3: var (name, age) = getUser(). No .first/.second awkwardness.
Code Examples
Alice: 95 Alice alice@example.com true Bob scored 70
Common Mistakes
- โUsing Records for complex domain objects โ they're for lightweight, anonymous value grouping, not full entities
- โMixing positional and named fields without clear naming โ reduces readability
Interview Tip
Records eliminate the 'return a Map and lose type safety' anti-pattern. Mention that Records work with Dart 3 pattern matching for exhaustive destructuring.