Collections in Dart

What are Collections?

A collection is an object that represents a group of objects, which are called elements.

A collection can be empty, or it can contain many elements. Depending on the purpose, collections can have different structures and implementations.

These are some of the most common collection types:

  1. List: Used to read elements by their indexes.
  2. Set: Used to contain elements that can occur only once.
  3. Map: Used to read elements using a key.

In Dart, both List and Set are Iterable, so they have the same methods and properties as the Iterable class.

A Map uses a different data structure internally, depending on its implementation. For example, HashMap uses a hash table in which the elements (also called values) are obtained using a key.

Elements of a Map can also be read as Iterable objects by using the map’s entries or values property.

Collection if

The collection if used to build list using if condition.

Manipulate the items of a list before adding them to another list:

main() {
  bool isVacancyAvailable = true;
  var siteNavbar = [
    'Home',
    'Services',
    if (isVacancyAvailable) 'Careers',
    'Contact Us'
  ];
  print(siteNavbar); // [Home, Services, Careers, Contact Us]
}

Collection for

The collection for used to build list using repetition for condition.

Manipulate the items of a list before adding them to another list:

main() {
  var languages = ['Dart', 'Flutter', 'Angular', 'React'];

  // manipulate the items of a list to lower case before adding them to another list:
  var skills = ['javascript', for (var item in languages) item.toLowerCase()];

  // manipulate the items of a list add # before adding them to another list:
  var tags = ['#javascript', for (var item in languages) '#$item'];

  print(skills); // [javascript, dart, flutter, angular, react]

  print(tags); // [#javascript, #Dart, #Flutter, #Angular, #React]
}