Dart Collections Overview

In Dart, collections are essential structures that allow you to group and manage collections of objects efficiently. Collections in Dart consist mainly of three types: Lists, Sets, and Maps. Each type has its own unique properties and strengths, making them suitable for different use cases. In this article, we will delve into each of these collections, explore their features, and provide examples of how to maximize their usage in your Dart programs.

Lists

What is a List?

A List in Dart is an ordered collection of items. It is similar to arrays found in other programming languages and can hold elements of any data type, including numbers, strings, objects, and even other collections. Lists in Dart support both fixed-length and growable versions.

Creating Lists

You can create a List in Dart with the following syntax:

// Fixed-length list
var fixedList = List<int>.filled(3, 0); // Creates a list of three 0s

// Growable list
var growableList = [1, 2, 3]; // Automatically creates a growable list

Accessing and Modifying Lists

Accessing elements in a List is straightforward. You can use the index of the item, which starts at 0:

var myList = ['apple', 'banana', 'cherry'];

// Accessing the first element
print(myList[0]); // Outputs: apple

// Modifying an element
myList[1] = 'blueberry';
print(myList); // Outputs: [apple, blueberry, cherry]

Common Operations

Lists offer various built-in methods, including:

  • Adding Items: Use add() to append an item to the end of the list.
  • Removing Items: Use remove() and removeAt() to delete an item by value or index.
  • Iterating Through a List:
for (var item in myList) {
  print(item);
}
  • Sorting and Reversing: Dart provides sort() and reversed methods to order your lists.

Example

Here's a simple example that showcases the creation and manipulation of a List:

void main() {
  var shoppingList = ['Eggs', 'Milk', 'Bread'];

  // Adding an item
  shoppingList.add('Butter');

  // Removing an item
  shoppingList.remove('Milk');

  // Printing the final shopping list
  print(shoppingList); // Outputs: [Eggs, Bread, Butter]
}

Sets

What is a Set?

A Set is a collection of unique items in Dart. It is unordered and does not allow duplicate values. Sets are particularly useful when you need to ensure that a collection contains only distinct elements.

Creating Sets

You can create a Set in Dart using the following syntax:

var mySet = <String>{}; // Empty set of strings

var numberSet = {1, 2, 3, 4}; // Set of integers

Adding and Removing Elements

Manipulating a Set is similar to a List, but with the guarantee that elements remain unique:

mySet.add('apple');  // Adding an item
mySet.add('banana');
mySet.add('apple');  // This won't add a duplicate

print(mySet); // Outputs: {apple, banana}

// Removing an item
mySet.remove('banana');
print(mySet); // Outputs: {apple}

Common Operations

Some useful methods for Sets include:

  • Checking Membership*: Use contains() to check if an element exists.
if (mySet.contains('apple')) {
  print('Apple is in the set.');
}
  • Iterating Through a Set: Similar to a List, you can iterate over a Set.
for (var item in numberSet) {
  print(item);
}

Example

Here's an example showcasing the usage of a Set:

void main() {
  var uniqueFruitSet = <String>{};

  // Adding fruits
  uniqueFruitSet.add('apple');
  uniqueFruitSet.add('banana');
  uniqueFruitSet.add('apple'); // Won't be added

  // Print the unique fruits
  print(uniqueFruitSet); // Outputs: {apple, banana}
}

Maps

What is a Map?

A Map is a collection of key-value pairs. Keys must be unique, and they are used to access the corresponding values. Maps are particularly useful when you need to associate a specific value with a unique identifier.

Creating Maps

Maps can be created using the following syntax:

var myMap = <String, int>{}; // Empty map

var fruitPrices = {
  'apple': 1,
  'banana': 2,
  'cherry': 3,
}; // Map with initial key-value pairs

Accessing and Modifying Maps

You can access and modify values in a Map by using their respective keys:

print(fruitPrices['banana']); // Outputs: 2

// Modifying a value
fruitPrices['banana'] = 2.5; // Change price of banana
print(fruitPrices); // Outputs: {apple: 1, banana: 2.5, cherry: 3}

Common Operations

Maps come with a variety of built-in methods, including:

  • Adding Entries: You can add new key-value pairs easily.
fruitPrices['orange'] = 4; // Adding an orange price
  • Removing Entries: Use remove() to delete a key-value pair.
fruitPrices.remove('cherry');
  • Iterating through a Map:
fruitPrices.forEach((key, value) {
  print('$key: $value');
});

Example

Here’s a simple example of using a Map:

void main() {
  var bookPrices = {
    '1984': 15.0,
    'Brave New World': 12.5,
    'Fahrenheit 451': 10.9,
  };

  // Modifying an existing price
  bookPrices['1984'] = 16.0;

  // Add a new entry
  bookPrices['The Great Gatsby'] = 14.0;

  // Print all book prices
  bookPrices.forEach((book, price) {
    print('$book: \$$price');
  });
}

Conclusion

Dart's collections—Lists, Sets, and Maps—are powerful tools that enable effective management and organization of data in your applications. By understanding their characteristics and functionalities, you can choose the appropriate collection type based on your specific needs.

Using Lists for ordered sequences, Sets for uniqueness, and Maps for key-value relationships, you can create efficient and clear data structures in your Dart programs. Remember to explore the various built-in functions available in each collection type to optimize your code and enhance its readability. Happy coding!