Skip to main content

Command Palette

Search for a command to run...

4. Exploring Collections in Dart: Lists, Maps, and Sets

Updated
4 min read

1. Lists in Dart

What are Lists?

A List in Dart is an ordered collection of elements, where each element can be accessed via an index. Lists are ideal for managing sequences of data.

Creating Lists

Dart supports both mutable and immutable lists:

  • Mutable List:

      List<int> numbers = [1, 2, 3];
      numbers.add(4); // Adds 4 to the list
    
  • Immutable List:

      var immutableList = const [1, 2, 3];
      // immutableList.add(4); // Error: Cannot modify an immutable list
    

Common List Operations

  • Accessing Elements:

      print(numbers[0]); // Output: 1
    
  • Adding Elements:

      numbers.add(5); // Adds 5 to the end
      numbers.insert(1, 10); // Inserts 10 at index 1
    
  • Removing Elements:

      numbers.remove(3); // Removes the first occurrence of 3
      numbers.removeAt(2); // Removes the element at index 2
    
  • Iterating Over a List:

      for (var num in numbers) {
        print(num);
      }
    
  • Filtering and Mapping:

      var evenNumbers = numbers.where((num) => num.isEven).toList();
      var doubledNumbers = numbers.map((num) => num * 2).toList();
    

Advanced List Features

  • Spread Operator (...): Combines multiple lists or adds elements to a list:

      var combined = [...numbers, 6, 7];
    
  • Null-Aware Spread Operator (...?): Adds elements from another list only if it’s non-null:

      var optionalList;
      var result = [...?optionalList, 8, 9]; // Works even if optionalList is null
    

    • GENERRAL NULL SAFETY OPERATOR

    • ?.: Safely accesses a property or method if the object is not null. If it's null, it does nothing.

    • ??=: Assigns a value only if the variable is null.

2. Maps in Dart

What are Maps?

A Map is a collection of key-value pairs where keys are unique. Maps are perfect for storing data with a clear association, like JSON-like structures.

Creating Maps

  • Literal Syntax:

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

      var emptyMap = <String, int>{};
    

Common Map Operations

  • Accessing Values:

      print(ages['Alice']); // Output: 30
    
  • Adding and Updating:

      ages['Charlie'] = 35; // Adds a new key-value pair
      ages['Alice'] = 31;   // Updates the value for 'Alice'
    
  • Removing Entries:

      ages.remove('Bob'); // Removes the entry with key 'Bob'
    
  • Checking Existence:

      print(ages.containsKey('Alice')); // true
      print(ages.containsValue(25));   // false
    
  • Iterating Over a Map:

      ages.forEach((key, value) {
        print('$key is $value years old');
      });
    
  • Transforming Maps:

      var updatedAges = ages.map((key, value) => MapEntry(key, value + 1));
    

Advanced Map Features

  • Maps are particularly useful for managing hierarchical data and JSON-like structures:

      Map<String, dynamic> user = {
        'name': 'Alice',
        'age': 30,
        'address': {'city': 'New York', 'zip': '10001'}
      };
      print(user['address']['city']); // Output: New York
    

3. Sets in Dart

What are Sets?

A Set is an unordered collection of unique elements, ensuring that no duplicates exist. Sets are useful for operations like union, intersection, and difference.

Creating Sets

  • Literal Syntax:

      Set<int> numbers = {1, 2, 3};
    
  • Empty Set:

      var emptySet = <int>{};
    

Common Set Operations

  • Adding Elements:

      numbers.add(4); // Adds 4
    
  • Removing Elements:

      numbers.remove(2); // Removes 2
    
  • Checking for Membership:

      print(numbers.contains(3)); // true
    
  • Set Operations:

      var setA = {1, 2, 3};
      var setB = {3, 4, 5};
    
      print(setA.union(setB));       // {1, 2, 3, 4, 5}
      print(setA.intersection(setB)); // {3}
      print(setA.difference(setB));  // {1, 2}
    

Iterating Over a Set

for (var num in numbers) {
  print(num);
}

4. Advanced Collection Manipulation

Filtering and Transforming

Dart collections come with methods like map, where, and reduce for processing data:

var numbers = [1, 2, 3, 4, 5];
var doubled = numbers.map((n) => n * 2).toList(); // [2, 4, 6, 8, 10]
var evenNumbers = numbers.where((n) => n.isEven).toList(); // [2, 4]

Combining and Merging

var listA = [1, 2];
var listB = [3, 4];
var combined = [...listA, ...listB]; // [1, 2, 3, 4]

Sorting

var numbers = [5, 2, 8, 1];
numbers.sort(); // Ascending order: [1, 2, 5, 8]
numbers.sort((a, b) => b.compareTo(a)); // Descending order: [8, 5, 2, 1]

5. Best Practices for Using Collections

  1. Choose the Right Collection Type: Use Lists for ordered data, Sets for unique elements, and Maps for key-value associations.

  2. Use Immutable Collections: When the data shouldn't change, prefer const or immutable collections to improve safety and performance.

  3. Leverage Spread Operators: Simplify list and set concatenation using ... and ...?.

  4. Optimize Searches: Use Set for faster lookups compared to List.

  5. Use Built-in Methods: Dart’s rich collection APIs provide ready-to-use methods for filtering, transforming, and iterating.


More from this blog

sangama

1285 posts