tezvyn:

Dart Collections: Choosing List, Set, or Map

AI-drafted, machine-checkedSource: dart.devintermediate

Dart collections organize data: use a List for ordered items, a Set for unique items, and a Map for key-value pairs. This choice is fundamental for storing UI widgets or parsing JSON. The common footgun is using a List for lookups, which is slow; use.

WHY IT EXISTS Programs need to store groups of related objects. But "a group" can mean an ordered sequence, a collection of unique items, or a dictionary-style lookup table. Dart provides specialized collections for each job to ensure code is both correct and performant, preventing bugs and slow operations.

THE MENTAL MODEL Think of collections as different containers. A List is a numbered rack of shoeboxes; you access items by their position (index). A Set is a bag of marbles; you can quickly check if a specific marble is in the bag, but there are no duplicates and no guaranteed order. A Map is a dictionary; you look up a word (key) to find its definition (value).

HOW IT WORKS A List is an ordered, indexable collection, like an array in other languages. It allows duplicates and is created with square brackets: var scores = [98, 87, 98];. You access elements by index, like scores[0].

A Set is an unordered collection of unique items. It's created with curly braces: var tags = {'flutter', 'dart'};. Adding an existing element does nothing. Its main job is fast existence checks.

A Map is a collection of key-value pairs. Each key must be unique. It's created with curly braces and colons: var user = {'id': 123, 'name': 'Alex'};. It provides very fast value lookups based on a key, like user['name'].

WHEN TO USE IT Use a List when order matters, like items in a ListView, steps in a wizard, or a history of events. Use a Set when uniqueness is critical, like tracking selected filter options or de-duplicating items from another source. Use a Map when you need to associate one value with another, like parsing JSON data, storing app settings, or caching objects by their ID.

WHEN NOT TO USE IT The biggest footgun is using a List when you need fast lookups. Calling List.contains() on a large list is very slow because it must check every element. If you need to frequently check for an item's existence, use a Set or a Map, which are optimized for this and provide near-instantaneous lookups.

ONE CANONICAL EXAMPLE Imagine a shopping cart. The items in the cart are a List, because the user might add the same item twice and their order of addition might matter. The set of unique products available in the store could be a Set, for quick checks on availability. A single product's details (like 'price', 'name', 'SKU') would be stored in a Map.

Read the original → dart.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.