When to use Lists, Sets, Maps or Iterables

When to use Lists, Sets, Maps or Iterables

Table of contents

Dart provides several options, including lists, sets, maps, and the more abstract concept of Iterables.

Each has its own strengths and weaknesses, making them suitable for different scenarios.

In this blog post, we'll explore when to use lists, sets, maps, and Iterables in Dart, helping you make informed decisions in your code.

List:

  • You need an ordered collection of elements.

  • You need to access elements by index.

  • Duplicate elements are allowed.

  • You want a dynamic-size collection.

List<String> fruits = ['apple', 'banana', 'orange'];

Sets:

  • You need an unordered collection of unique elements.

  • You want to ensure that elements are distinct.

  • You don't need to access elements by index.

Set<String> uniqueFruits = {'apple', 'banana', 'orange'};

Maps:

  • You need to associate keys with values.

  • You want to perform lookups based on keys.

  • You want a key-value pair data structure.

Map<String, int> ages = {'Alice': 25, 'Bob': 30, 'Charlie': 22};

Iterables:

  • You want to represent a sequence of elements that can be iterated.

  • You want to use common iterable operations like forEach, map, where, etc.

  • You don't need direct access to elements by index.

  • You are creating custom iterable classes.

Iterable<int> countdown = CountdownIterable(5, 1);