Collections in Dart

Work with Lists, Maps, and Sets

Collections in Dart


Definition

Collections are data structures that store multiple values in a single variable. They're essential for managing groups of related data like lists of numbers, lists of names, or key-value pairs.


Three Main Collection Types


**List**

An ordered, indexed collection of items.

  • Index starts at 0
  • Access items using index: `list[0]`
  • Items can be duplicated
  • Order matters

  • `

    List numbers = [1, 2, 3, 4, 5];

    var first = numbers[0]; // 1

    `

    **Map**

    A collection of key-value pairs. Use a key to find a value.

  • Keys are unique
  • Fast lookup by key
  • Like a dictionary

  • `

    Map ages = {

    'Alice': 25,

    'Bob': 30,

    };

    `

    **Set**

    An unordered collection of unique items.

  • No duplicates allowed
  • No specific order
  • Fast membership testing

  • `

    Set fruits = {'Apple', 'Banana', 'Orange'};

    `

    Common List Operations


  • `length`: Number of items
  • `add()`: Add an item
  • `remove()`: Remove an item
  • `contains()`: Check if item exists
  • `forEach()`: Loop through items
  • Cell2Dart
    // List example with indexing List<int> numbers = [10, 20, 30, 40, 50]; int sum = 0; for (int i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; print('Index $i: ${numbers[i]}'); } print('Sum: $sum');

    Accessing Collections


    List Access

  • Use index: `numbers[0]` gets first item
  • Indices: 0, 1, 2, ..., length-1
  • Out of bounds = error!

  • Map Access

  • Use key: `ages['Alice']` gets value
  • Keys: whatever you define

  • Iteration

  • `for(int i = 0; i < list.length; i++)` - traditional
  • `for(var item in list)` - for-in loop
  • `list.forEach((item) => print(item))` - functional
  • Cell4Dart
    // Map and for-in loop example Map<String, int> ages = { 'Alice': 25, 'Bob': 30, 'Charlie': 35, }; // Loop through entries for (String name in ages.keys) { print('$name is ${ages[name]} years old'); } // List with for-in List<String> fruits = ['Apple', 'Banana', 'Orange']; for (String fruit in fruits) { print('Fruit: $fruit'); }

    Practice

    CellcustomDart
    List<String> fruits = ['Apple', 'Banana', 'Orange']; for (String fruit in fruits) { print(fruit); }
    Run code to see collection values