DartBasic 2 min read

Dart Iterable, map, where and fold: summarize invoices

Transform, filter and aggregate typed data while understanding lazy evaluation.

On this page

An invoice report often selects outstanding items and computes a total. Express each stage with a name so it can be inspected or tested. Iterable operations let you describe a sequence without necessarily creating a new list at every step.

Worked example

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

main.dart
void main() {
  final invoices = [
    (customer: 'Asha', paise: 12000, paid: false),
    (customer: 'Dev', paise: 8000, paid: true),
    (customer: 'Mira', paise: 5000, paid: false),
  ];
  final outstanding = invoices.where((invoice) => !invoice.paid).toList();
  final total = outstanding.fold<int>(0, (sum, invoice) => sum + invoice.paise);
  print(outstanding.map((invoice) => invoice.customer).join(', '));
  print('Outstanding: $total paise');
}

Follow the data and control flow

Filtering chooses Asha and Mira. fold<int> starts with zero and accumulates 17000 paise. Unlike reduce, a fold with an initial value also has a defined result for an empty collection. The named record fields make the example readable without introducing a full invoice class yet.

where and map are generally lazy. Calling toList here captures the selection once, so later consumers see that snapshot. If the original collection can change, decide whether a live lazy view or a stable materialized result is appropriate.

A mistake to avoid

Side effects inside a lazy transformation can run again when the iterable is traversed again. Do not put a network call or counter mutation inside a mapper merely because it appears to run once in a print statement. Avoid sorting a shared source just to calculate an aggregate.

Practice and verification

Mark all invoices paid and verify the total becomes zero. Add an average calculation that handles an empty selection explicitly. Compare fold and reduce on empty data and explain which contract your report requires.

How this topic connects

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.