flutter
/

Dart Collection Methods – Complete Guide with Examples

Last Sync: Today

On this page

34
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart Collection Methods – Complete Guide with Examples

What are Collection Methods?

Dart provides a rich set of methods to work with collections like List, Set, and Map. These methods allow you to iterate, transform, filter, combine, and reduce collections in a functional and expressive way. Most of these methods come from the Iterable class, which List and Set implement, and from the Map class itself. Mastering these methods will make your code more concise, readable, and less error‑prone.

  1. Iteration Methods

forEach()

Executes a function on each element of the collection. It does not return a value (just performs side effects).

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3];
  numbers.forEach(print); // prints 1, 2, 3
  
  var fruits = {'apple', 'banana'};
  fruits.forEach((fruit) => print('I like $fruit'));
}

  1. Transformation Methods

map()

Transforms each element into a new value. Returns a new lazy Iterable; call toList() or toSet() to materialise.

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3];
  var squares = numbers.map((n) => n * n).toList();
  print(squares); // [1, 4, 9]
}

expand()

Transforms each element into zero or more elements. Returns a flattened iterable.

DARTRead-only
1
void main() {
  var pairs = [[1, 2], [3, 4]];
  var flattened = pairs.expand((pair) => pair).toList();
  print(flattened); // [1, 2, 3, 4]
}

  1. Filtering Methods

where()

Returns a new lazy iterable containing only elements that satisfy the given predicate.

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3, 4, 5];
  var even = numbers.where((n) => n % 2 == 0).toList();
  print(even); // [2, 4]
}

firstWhere(), lastWhere(), singleWhere()

Find the first, last, or only element matching a condition. Provide an optional orElse function if no element is found.

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3, 4, 5];
  var firstEven = numbers.firstWhere((n) => n % 2 == 0); // 2
  var lastEven = numbers.lastWhere((n) => n % 2 == 0);   // 4
  var single = numbers.singleWhere((n) => n == 3);       // 3
}

  1. Checking Conditions

any() and every()

any returns true if at least one element satisfies the condition. every returns true if all elements satisfy the condition.

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3];
  print(numbers.any((n) => n > 2));  // true
  print(numbers.every((n) => n > 0)); // true
}

contains()

Checks if the collection contains a specific element (uses == equality).

DARTRead-only
1
void main() {
  var fruits = ['apple', 'banana'];
  print(fruits.contains('banana')); // true
}

  1. Reduction Methods

reduce()

Combines all elements using a given function. The collection must not be empty. The result type is the same as the element type.

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3, 4];
  var sum = numbers.reduce((a, b) => a + b); // 10
  var product = numbers.reduce((a, b) => a * b); // 24
}

fold()

Similar to reduce, but takes an initial value and can return a different type. Safe for empty collections.

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3];
  var sum = numbers.fold(0, (prev, element) => prev + element); // 6
  var concatenated = numbers.fold('', (prev, element) => '$prev$element'); // '123'
}

  1. Sorting and Ordering

sort() (List only)

Sorts the list in place. You can provide a custom comparison function.

DARTRead-only
1
void main() {
  var numbers = [3, 1, 4, 2];
  numbers.sort(); // [1, 2, 3, 4]
  
  var names = ['Charlie', 'Alice', 'Bob'];
  names.sort((a, b) => a.length.compareTo(b.length)); // sort by length
  print(names); // [Bob, Alice, Charlie]
}

reversed (List only)

Returns an iterable of the elements in reverse order. To get a list, call toList().

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3];
  var reversed = numbers.reversed.toList(); // [3, 2, 1]
}

shuffle() (List only)

Randomly shuffles the list in place.

DARTRead-only
1
import 'dart:math';

void main() {
  var numbers = [1, 2, 3, 4, 5];
  numbers.shuffle(); // random order
}

  1. Taking and Skipping

take(), skip()

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3, 4, 5];
  var firstTwo = numbers.take(2).toList(); // [1, 2]
  var afterTwo = numbers.skip(2).toList();  // [3, 4, 5]
}

takeWhile(), skipWhile()

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3, -1, 4];
  var positive = numbers.takeWhile((n) => n > 0).toList(); // [1, 2, 3]
  var afterNegative = numbers.skipWhile((n) => n > 0).toList(); // [-1, 4]
}

  1. Converting Between Collections

DARTRead-only
1
void main() {
  var list = [1, 2, 3, 2];
  var set = list.toSet(); // {1, 2, 3}
  var newList = set.toList(); // [1, 2, 3]
  
  var map = {1: 'one', 2: 'two'};
  var entries = map.entries.toList(); // list of MapEntry objects
}

  1. Map‑Specific Methods

keys, values, entries

DARTRead-only
1
void main() {
  var map = {'a': 1, 'b': 2, 'c': 3};
  print(map.keys);   // (a, b, c)
  print(map.values); // (1, 2, 3)
  print(map.entries); // (MapEntry(a: 1), MapEntry(b: 2), MapEntry(c: 3))
}

putIfAbsent()

DARTRead-only
1
void main() {
  var map = {'a': 1};
  map.putIfAbsent('b', () => 2); // adds b:2
  map.putIfAbsent('a', () => 99); // does nothing, a already exists
}

update() and updateAll()

DARTRead-only
1
void main() {
  var map = {'a': 1, 'b': 2};
  map.update('a', (value) => value * 10); // a:10
  map.update('c', (value) => 3, ifAbsent: () => 3); // adds c:3
  map.updateAll((key, value) => value * 2); // double all values
}

removeWhere()

DARTRead-only
1
void main() {
  var map = {'a': 1, 'b': 2, 'c': 3};
  map.removeWhere((key, value) => value.isOdd); // removes a and c
}

  1. Set‑Specific Methods

union(), intersection(), difference()

DARTRead-only
1
void main() {
  var a = {1, 2, 3};
  var b = {3, 4, 5};
  print(a.union(b));        // {1, 2, 3, 4, 5}
  print(a.intersection(b)); // {3}
  print(a.difference(b));   // {1, 2}
}

retainAll() and removeAll()

DARTRead-only
1
void main() {
  var set = {1, 2, 3, 4};
  set.retainAll({2, 3});   // keeps only 2 and 3
  set.removeAll({3});       // removes 3, set now {2}
}

Chaining Methods

Many collection methods return iterables, so you can chain them to perform complex transformations in a readable way.

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3, 4, 5, 6];
  var result = numbers
      .where((n) => n.isEven)            // [2, 4, 6]
      .map((n) => n * n)                 // [4, 16, 36]
      .toList();
  print(result); // [4, 16, 36]
}

Complete Example

DARTRead-only
1
void main() {
  // Sample data: list of people with name and age
  var people = [
    {'name': 'Alice', 'age': 30},
    {'name': 'Bob', 'age': 25},
    {'name': 'Charlie', 'age': 35},
    {'name': 'Diana', 'age': 28},
  ];
  
  // 1. Get names of people older than 28
  var namesOver28 = people
      .where((person) => person['age'] > 28)
      .map((person) => person['name'])
      .toList();
  print('Over 28: $namesOver28'); // [Alice, Charlie]
  
  // 2. Calculate average age
  double totalAge = people.fold(0, (sum, person) => sum + person['age']);
  double averageAge = totalAge / people.length;
  print('Average age: $averageAge');
  
  // 3. Sort by age (ascending)
  var sorted = [...people]..sort((a, b) => a['age'].compareTo(b['age']));
  print('Sorted by age: $sorted');
}

Key Takeaways

    • forEach performs an action on each element.
    • map transforms each element into something new.
    • where filters elements based on a condition.
    • any and every test conditions across the collection.
    • reduce and fold combine elements into a single value.
    • Lists have additional methods like sort, shuffle, and reversed.
    • Maps have keys, values, entries, putIfAbsent, update, and removeWhere.
    • Sets support mathematical operations: union, intersection, difference.
    • Methods can be chained to create powerful data processing pipelines.

Try it yourself

void main() {
  var numbers = [5, 2, 8, 1, 9, 3];
  
  // Chain methods: filter even numbers, square them, sort descending
  var result = numbers
      .where((n) => n.isEven)
      .map((n) => n * n)
      .toList()
      ..sort((a, b) => b.compareTo(a));
  
  print('Original: $numbers');
  print('Processed: $result');
}

Test Your Knowledge

Q1
of 4

What does the `map()` method return?

A
A new List
B
A new Iterable (lazy)
C
A new Set
D
The original collection modified
Q2
of 4

Which method would you use to check if at least one element in a list satisfies a condition?

A
every()
B
contains()
C
any()
D
some()
Q3
of 4

What is the difference between `reduce` and `fold`?

A
`reduce` works on empty collections, `fold` does not
B
`fold` takes an initial value and can return a different type
C
There is no difference
D
`reduce` can only be used on numbers
Q4
of 4

Which method is only available on List, not on Iterable?

A
map()
B
where()
C
sort()
D
forEach()

Frequently Asked Questions

What is the difference between `map()` and `forEach()`?

map() returns a new lazy iterable containing the results of applying a function to each element. It is used for transformation. forEach() executes a function on each element for side effects and does not return anything.

Can I use `where()` on a Map?

Maps do not directly have a where() method, but you can use entries.where() to filter entries based on key or value, then convert back to a map with Map.fromEntries().

What's the difference between `reduce()` and `fold()`?

reduce() combines elements using a function and returns a value of the same type as the elements. It cannot be used on an empty collection. fold() takes an initial value of any type and can combine elements into a different type; it works even on empty collections.

Are collection methods lazy?

Methods like map(), where(), take(), skip() are lazy – they don't process elements until you iterate over the result (e.g., with toList() or forEach). Methods like reduce(), fold(), any(), every() are eager and process immediately.

How do I sort a list in descending order?

You can pass a custom comparator to sort(): list.sort((a, b) => b.compareTo(a)) for numbers, or use reversed after sorting: list.sort(); var reversed = list.reversed.toList();

Previous

dart map

Next

dart spread operator

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.