Skip to content
Blog

Reshaping Dart Data with map, where, fold, and expand

Master functional collection transformations in Dart 3: filtering with where, transforming with map, aggregating with fold/reduce, and flattening with expand.

Published on • December 5, 2026

AI Assistant

Dart embraces functional programming idioms when working with iterables. Rather than writing verbose for loops with mutable accumulator variables, Dart’s Iterable interface provides higher-order methods to reshape, filter, aggregate, and flatten datasets cleanly and efficiently.

In this tutorial, we will examine the four core transformation pillars: map, where, fold, and expand, examining lazy evaluation mechanics, type signatures, and performance characteristics.


The Big Four Transformation Methods

Data Reshaping Pipeline:
[Initial Collection]
         │
         ▼
       where()   ──► Filters elements based on boolean predicate
         │
         ▼
        map()    ──► Projects each element to a new type or shape
         │
         ▼
       expand()  ──► Flattens 1-to-many nested iterables into a 1D sequence
         │
         ▼
        fold()   ──► Accumulates elements into a single scalar result

1. where: Filtering Collections

where returns a new lazy iterable containing only elements that satisfy a predicate bool Function(E element):

void main() {
  final numbers = [12, 5, 8, 130, 44, 3];

  // Filter only even numbers greater than 10
  final filtered = numbers.where((n) => n % 2 == 0 && n > 10).toList();
  print(filtered); // [12, 130, 44]
}

Specialized Type Filtering with whereType<T>()

When you have a mixed list and need to extract elements of a specific runtime subtype, use whereType<T>() instead of manual is checks:

final mixed = [1, 'Dart', 3.14, 'Flutter', true];
final strings = mixed.whereType<String>().toList(); // List<String>
print(strings); // [Dart, Flutter]

2. map: 1-to-1 Element Transformation

map converts every element of type E to a new element of type T:

class User {
  final String id;
  final String name;
  User(this.id, this.name);
}

void main() {
  final users = [User('u1', 'Alice'), User('u2', 'Bob')];

  // Extract names into List<String>
  final names = users.map((u) => u.name).toList();
  print(names); // [Alice, Bob]
}

Performance Note: map and where are lazy. They do not allocate new lists until an eager terminal method like .toList(), .toSet(), or .first is called.


3. expand: 1-to-Many Flattening

When an element maps to a collection, using map produces an Iterable<List<T>> (nested list). expand flattens these inner iterables into a single contiguous stream:

class Department {
  final String name;
  final List<String> employees;
  Department(this.name, this.employees);
}

void main() {
  final departments = [
    Department('Engineering', ['Alice', 'Bob']),
    Department('Design', ['Charlie', 'Dana']),
  ];

  // Using map produces Iterable<List<String>>: [['Alice', 'Bob'], ['Charlie', 'Dana']]
  // Using expand flattens to a single Iterable<String>:
  final allEmployees = departments.expand((dept) => dept.employees).toList();

  print(allEmployees); // [Alice, Bob, Charlie, Dana]
}

4. fold and reduce: Aggregation

reduce

Collapses elements of type E using an associative operator E Function(E value, E element). Throws an error on empty collections:

final numbers = [10, 20, 30, 40];
final sum = numbers.reduce((acc, curr) => acc + curr); // 100

fold

A safer, more flexible aggregator. It takes an explicit initial value of type R, works on empty collections, and can return a type different from the list elements:

void main() {
  final orders = [
    {'item': 'Book', 'price': 15.0},
    {'item': 'Pen', 'price': 3.5},
    {'item': 'Notebook', 'price': 8.0},
  ];

  // Accumulate total dollar price (double) from list of maps
  final totalRevenue = orders.fold<double>(
    0.0,
    (total, order) => total + (order['price'] as double),
  );

  print('Total: \$$totalRevenue'); // Total: $26.5
}

Composing a Real-World Functional Pipeline

Let’s combine all four operators to solve a practical data extraction problem: finding all unique tags from active, published articles and generating a frequency summary:

class Article {
  final String title;
  final bool isPublished;
  final List<String> tags;
  Article(this.title, this.isPublished, this.tags);
}

void main() {
  final articles = [
    Article('Dart 3 Features', true, ['dart', 'language']),
    Article('Flutter Web 2026', false, ['flutter', 'web']), // draft, skip
    Article('ADK Agents', true, ['ai', 'adk', 'dart']),
  ];

  // Chain: Filter -> Flatten -> Group Frequency via fold
  final tagFrequencies = articles
      .where((a) => a.isPublished)
      .expand((a) => a.tags)
      .fold<Map<String, int>>({}, (map, tag) {
        map[tag] = (map[tag] ?? 0) + 1;
        return map;
      });

  print(tagFrequencies);
  // {dart: 2, language: 1, ai: 1, adk: 1}
}

Best Practices

  • Avoid Redundant Conversions: Do not call .toList() in intermediate pipeline steps; only call .toList() or .toSet() at the final consumption point.
  • Prefer fold over reduce: fold is null-safe on empty collections and allows custom accumulator types.
  • Use whereType<T>(): Avoid list.where((x) => x is T).cast<T>() in favor of the cleaner and safer list.whereType<T>().