TExcelTAD
Home › Flutter › Dart Collections

Dart Collections

Apps are full of groups of data: a list of messages, a set of selected tags, a map from product IDs to prices. Dart's three core collection types are List, Set and Map. All of them are generic — List<String> holds only strings — so the compiler can check what goes in and comes out.

Type Literal Ordered? Duplicates? Access by
List<E> [1, 2, 3] Yes Yes Index list[0]
Set<E> {1, 2, 3} Insertion order No Membership set.contains(x)
Map<K, V> {'a': 1} Insertion order Unique keys Key map['a']

Lists

A List is an ordered, indexable sequence — Dart's version of an array. Lists grow and shrink as needed.

dart · try it yourself
void main() {
  var tasks = <String>['Buy milk', 'Write code'];

  tasks.add('Walk dog');
  tasks.insert(0, 'Wake up');
  print(tasks);
  print('First: ${tasks.first}, last: ${tasks.last}');
  print('Count: ${tasks.length}');
  print(tasks[1]);

  tasks.remove('Buy milk');
  tasks.removeAt(0);
  print(tasks);
  print(tasks.contains('Walk dog'));
  print(tasks.indexOf('Walk dog'));
}
[Wake up, Buy milk, Write code, Walk dog]
First: Wake up, last: Walk dog
Count: 4
Buy milk
[Write code, Walk dog]
true
1

Indexes start at 0. Reading an index that doesn't exist throws a RangeError, so check length first or use elementAtOrNull style helpers when unsure.

Note: A const list such as const [1, 2, 3] is unmodifiable — calling add on it throws at runtime. List.unmodifiable(...) creates one at runtime.

Spread and collection-if

The spread operator ... inserts all elements of another collection; ...? does the same but ignores null. Combined with collection if and for, you can build collections declaratively.

dart · try it yourself
void main() {
  var base = [1, 2, 3];
  List<int>? extra;
  var isAdmin = true;

  var combined = [0, ...base, ...?extra, if (isAdmin) 99];
  print(combined);

  var copy = [...base];
  copy.add(4);
  print('base=$base copy=$copy');
}
[0, 1, 2, 3, 99]
base=[1, 2, 3] copy=[1, 2, 3, 4]

Transforming collections

Lists (and every Iterable) have functional methods. Most of them are lazy and return an Iterable — call .toList() when you need a list again.

Method Purpose
map(f) Transform each element
where(test) Keep elements that pass a test
firstWhere(test) First matching element
any(test) / every(test) Does any / every element match?
fold(initial, f) Combine into a single value
reduce(f) Like fold, starting from the first element
sort([compare]) Sort in place
take(n) / skip(n) First n / all but the first n
dart · try it yourself
void main() {
  var prices = [12.0, 3.5, 40.0, 7.25];

  var cheap = prices.where((p) => p < 10).toList();
  var labels = prices.map((p) => '\${p.toStringAsFixed(2)}').toList();
  var total = prices.fold(0.0, (sum, p) => sum + p);

  print(cheap);
  print(labels);
  print(total);
  print(prices.any((p) => p > 30));
  print(prices.every((p) => p > 1));

  var sorted = [...prices]..sort();
  print(sorted);
  var byDesc = [...prices]..sort((a, b) => b.compareTo(a));
  print(byDesc.take(2).toList());
}
[3.5, 7.25]
[$12.00, $3.50, $40.00, $7.25]
62.75
true
true
[3.5, 7.25, 12.0, 40.0]
[40.0, 12.0]

Sets

A Set stores each value at most once. It's ideal for "is this selected?" checks and for removing duplicates.

dart · try it yourself
void main() {
  var tags = <String>{'dart', 'flutter'};
  tags.add('dart');      // ignored: already present
  tags.add('mobile');
  print(tags);
  print(tags.length);

  var other = {'flutter', 'web'};
  print(tags.union(other));
  print(tags.intersection(other));
  print(tags.difference(other));

  var unique = [3, 1, 3, 2, 1].toSet().toList();
  print(unique);
}
{dart, flutter, mobile}
3
{dart, flutter, mobile, web}
{flutter}
{dart, mobile}
[3, 1, 2]

Tip: {} on its own creates an empty Map, not a Set. Write <String>{} for an empty set.

Maps

A Map associates keys with values. Looking up a missing key returns null, so the result type of map[key] is nullable.

dart · try it yourself
void main() {
  var stock = <String, int>{'apple': 5, 'pear': 0};

  stock['banana'] = 12;          // add
  stock['apple'] = 4;            // update
  stock.update('pear', (n) => n + 3);
  stock.putIfAbsent('kiwi', () => 1);

  print(stock);
  print(stock['apple']);
  print(stock['grape']);         // missing key
  print(stock['grape'] ?? 0);
  print(stock.containsKey('kiwi'));
  print(stock.keys.toList());
  print(stock.values.reduce((a, b) => a + b));

  for (final MapEntry(:key, :value) in stock.entries) {
    if (value > 3) print('$key has $value');
  }

  stock.remove('kiwi');
  print(stock.length);
}
{apple: 4, pear: 3, banana: 12, kiwi: 1}
4
null
0
true
[apple, pear, banana, kiwi]
20
apple has 4
banana has 12
3

The pattern MapEntry(:key, :value) destructures each entry into two variables — a Dart 3 feature.

Maps of lists, lists of maps

Real data (like JSON from a server) is usually nested. A typical shape is List<Map<String, dynamic>>:

dart
final users = [
  {'name': 'Hoa', 'age': 25},
  {'name': 'Quang', 'age': 31},
];
final names = users.map((u) => u['name'] as String).toList(); // [Hoa, Quang]

In the HTTP & JSON lesson you'll convert such maps into proper Dart classes.

Test yourself

What does {} create on its own?

  1. An empty Set
  2. An empty Map
  3. An empty List
  4. A compile error

What is the type of stock['grape'] when stock is Map<String, int>?

  1. int
  2. int?
  3. String
  4. dynamic

What does [1, 2, 3].where((n) => n > 1).toList() return?

  1. [1]
  2. [2, 3]
  3. [true, true]
  4. 2