DartBasic 2 min read

Dart collections: List, Set, Map and control flow

Choose lists, sets and maps, then use conditions and loops to express a small learning-plan example.

On this page

Collections group related values. Choose the collection from the question you need to answer: order suggests a list, uniqueness suggests a set, and looking up a value by key suggests a map.

Work with a small plan

main.dart
void main() {
  final lessons = ['Types', 'Functions', 'Classes'];
  final completed = {'Types'};
  final minutes = {'Types': 10, 'Functions': 15, 'Classes': 20};

  for (final lesson in lessons) {
    if (completed.contains(lesson)) continue;
    print('$lesson: ${minutes[lesson]} minutes');
  }
}

Pick the right shape

CollectionUseful propertyExample
ListStable sequence and indexed accessLessons in order
SetUnique membershipCompleted lesson IDs
MapValues addressed by keysEstimated minutes per lesson

An empty {} is a map literal. Use <String>{} when you mean an empty set of strings.

Make conditions readable

A short condition is often easier to maintain than a clever expression with several nested decisions. Give a complicated condition a descriptive local variable or function.

Trace one iteration and one missing lookup

For each lesson, the loop checks membership in the completed set. Completed items skip the remaining body; unfinished ones look up a duration and print it. The list provides order, the set provides membership and the map provides values by key.

Now remove a duration entry. A map lookup can return null even when the map’s values are integers, because the key may be absent. Decide what missing data means rather than forcing it with the non-null assertion.

Use null safety for that decision, then collection transformations to express filtering and totals without changing the original data.

Try it yourself

Add another lesson, mark two as complete and print the remaining total minutes. Decide what should happen if the map has no entry for one lesson instead of assuming every lookup succeeds.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.