DART / CHAPTER 03

Records and structural patterns

Intermediate

Represent small results with precise, destructurable shapes.

By the end of this chapter

  • Use named and positional record fields
  • Destructure a record without mutation
  • Match a shape before accessing its parts

The idea

Dart 3 records combine a fixed set of fields into an immutable aggregate. Positional fields are identified by position, while named fields are identified by name. A record type communicates the shape of a small result without requiring a new class. Record fields cannot be reassigned, although a referenced mutable object inside a field can still change.

Patterns can destructure a known record or test whether a value has an expected shape. Use a checked pattern when external or broadly typed data might not match. Named field order does not change a record’s named shape, but changing a field name does. Keep a class when behavior or a long-lived domain abstraction matters; records work well for focused multi-value results.

Dart example
void main() {
  final point = (x: 3, y: 5);
  final (x: left, y: top) = point;
  print(left + top);
  print(point == (y: 5, x: 3));
}
Result
8
true

Destructuring binds both fields, and named-field order does not change the record’s shape or values.

Try it yourself

Return a named record containing minimum and maximum values from a nonempty integer list.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Two records have identical named fields and values but list their fields in different orders. How does equality treat them?