DartIntermediate 2 min read

Dart records and destructuring: return a cart summary

Return several typed values without an untyped map or a single-use model class.

On this page

A cart summary needs a count and a subtotal. A record is useful when those values travel together locally but do not need identity, methods or a long-lived public model contract. Name fields when that makes the result easier to read.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
({int count, int totalPaise}) summarize(List<int> prices) => (
  count: prices.length,
  totalPaise: prices.fold(0, (sum, price) => sum + price),
);

void main() {
  final summary = summarize([12000, 8000, 5000]);
  final (:count, :totalPaise) = summary;
  print('$count items; $totalPaise paise');
  print(summary == (count: 3, totalPaise: 25000));
}

Follow the data and control flow

The return type names both fields and their integer types. Destructuring binds them to local variables without a string-key lookup. Records compare their shape and field values, so the final comparison is true for this data.

A positional record uses $1, $2 and later positional accessors. Named and positional fields are different shapes. Records themselves are immutable, but a mutable list stored inside one remains mutable; the container does not recursively freeze its fields.

A mistake to avoid

A record is not automatically a stable database or API format. For public contracts, decide field naming and serialization explicitly. If behavior, invariants or identity become important, a class can communicate those responsibilities better than a growing anonymous tuple.

Practice and verification

Add a maximum-price field and handle an empty cart. Compare two records with different named fields and explain why their shapes differ. Then decide whether a reusable invoice API should expose a record or an explicit model class.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.