Collections in Dart: Lists, Sets, and Maps Made Simple

Collections in Dart help you manage groups of related data. The three primary collection types are Lists, Sets, and Maps. Let’s break them down in a simple way.

1. Lists

A List is an ordered collection of items. You can think of it as a shopping list where the order matters.

Key Features:

  • Ordered: Items have a specific order.



  • Index-based: You access items using their index, starting from 0.
  • Can contain duplicates: You can have the same item multiple times.

Example Concept:

If you have a list of fruits, it could look like this:
['Apple', 'Banana', 'Cherry'].
You can access fruits[0] to get 'Apple'.

2. Sets

A Set is a collection of unique items. It’s like a box where no item can appear more than once.

Key Features:

  • Unordered: Items don’t have a specific order.
  • Unique items: No duplicates allowed.
  • Useful for membership tests: Fast lookups to check if an item exists.

Example Concept:

If you have a set of unique colors, it could look like this:
{'Red', 'Green', 'Blue'}.
If you try to add 'Red' again, it won’t be added.

3. Maps

A Map is a collection of key-value pairs. It’s like a dictionary where you look up a value based on a unique key.

Key Features:

  • Key-value pairs: Each key maps to a value.
  • Keys must be unique: No two keys can be the same.
  • Flexible values: Values can be of any data type.

Example Concept:

If you have a map of ages, it could look like this:
{'Alice': 30, 'Bob': 25}.
You can get Bob’s age with ages['Bob'], which would return 25.

Conclusion

Lists, Sets, and Maps are powerful collections in Dart that help you manage data effectively. Lists keep things in order, Sets ensure uniqueness, and Maps provide a way to associate keys with values. As you practice using these collections, you’ll find them essential for writing organized and efficient Dart code!


FINISH CHAPTER