Working with Maps in Dart

Maps are a collection of key-value pairs in Dart. They allow you to store data in a way that makes it easy to retrieve values based on their associated keys. Maps are commonly used for creating associative arrays or dictionaries, where each key is unique.

What Are Maps?

A map in Dart is an unordered collection of key-value pairs. Each key in a map must be unique, and it is used to access its corresponding value. Maps are useful when you need to associate values with unique identifiers.

Key Characteristics of Maps:

  • Key-Value Pairs: Each entry in a map consists of a unique key and an associated value.
  • Unordered: The entries in a map do not have a fixed order, meaning you cannot access them by index.
  • Dynamic Size: Maps can grow or shrink as needed, allowing for flexible data storage.

Syntax

To create a map in Dart, you can use the following syntax:

Map<keyType, valueType> mapName = {key1: value1, key2: value2};

Example

Here’s a simple example of creating and using a map:

void main() {
  Map<String, int> ages = {
    'Alice': 30,
    'Bob': 25,
    'Charlie': 35,
  };
  
  print(ages); // Output: {Alice: 30, Bob: 25, Charlie: 35} }

Use Cases

  • Associative Arrays: Maps are ideal for storing data in key-value pairs, such as user profiles or configuration settings.
  • Fast Lookups: Maps allow for quick access to values using their keys.
  • Dynamic Data Structures: Maps can be used to represent complex data structures like JSON objects.

Map Manipulations

You can perform various operations on maps, such as adding, removing, and accessing values.

Adding Key-Value Pairs

You can add entries to a map using the assignment operator:

void main() {
  Map<String, int> ages = {'Alice': 30};
  ages['Bob'] = 25; // Add a new key-value pair   
  print(ages); // Output: {Alice: 30, Bob: 25} 
  }

Removing Key-Value Pairs

You can remove an entry using the remove() method:

void main() {
  Map<String, int> ages = {
    'Alice': 30,
    'Bob': 25,
    'Charlie': 35,
  };
  ages.remove('Bob');
  print(ages); // Output: {Alice: 30, Charlie: 35} 
  }

Accessing Values

You can access a value using its key:

void main() {
  Map<String, int> ages = {
    'Alice': 30,
    'Bob': 25,
  };
  print(ages['Alice']); // Output: 30 
  }

Checking for Keys

To check if a key exists in a map, use the containsKey() method:

void main() {
  Map<String, int> ages = {
    'Alice': 30,
    'Bob': 25,
  };
  print(ages.containsKey('Bob')); // Output: true   
  print(ages.containsKey('Charlie')); // Output: false 
  }

Map Methods

Dart provides several built-in methods to manipulate maps. Here are some important ones:

  • addAll(Map<K, V> other): Adds all key-value pairs from another map.
  • remove(key): Removes the entry for the specified key.
  • clear(): Removes all entries from the map.
  • length: Returns the number of key-value pairs in the map.
  • keys: Returns an iterable of all keys in the map.
  • values: Returns an iterable of all values in the map.

Example of Map Methods

void main() {
  Map<String, int> ages = {
    'Alice': 30,
    'Bob': 25,
  };
  
  ages.addAll({'Charlie': 35, 'David': 28});
  print(ages); // Output: {Alice: 30, Bob: 25, Charlie: 35, David: 28} }

Important Keywords

  • Map: The main data type for creating maps in Dart.
  • var: A keyword that allows you to declare a variable without explicitly specifying its type. Dart infers the type based on the assigned value.
  • final: Used to declare a map that cannot be reassigned, although its contents can be modified.
  • const: Used to declare a compile-time constant map, which means the map cannot be modified at all.

Example of Final and Const Maps

void main() {
  final Map<String, int> ages = {
    'Alice': 30,
    'Bob': 25,
  };
  ages['Charlie'] = 35; // Allowed   
  // ages = {'David': 28}; // Not allowed, will cause an error 
  const Map<String, int> constants = {
    'X': 10,
    'Y': 20,
  };
  // constants['X'] = 15; // Not allowed, will cause an error }

Conclusion

Maps in Dart provide a powerful way to store collections of key-value pairs. They allow for quick access to values based on their associated keys and are ideal for representing associative arrays and complex data structures. Understanding how to create, manipulate, and utilize maps effectively is crucial for developing robust Dart applications.

Comparison Table: Maps vs. Lists

FeatureMapsLists
DuplicatesKeys must be unique; values can repeatCan contain duplicates
OrderUnorderedOrdered
Access MethodAccessed by keyAccessed by index
PerformanceFast lookups using keysSlower lookups
Use CasesKey-value pairs, associative arraysOrdered collections, indexing
Data StructureRepresents relationshipsRepresents sequences

 

PLAY QUIZ

What is a map in Dart?

An ordered collection of elements.

A collection of key-value pairs where each key is unique.

A fixed-size data structure.

A type of list that allows duplicates.