Skip to main content

What are Maps?

Maps (also called dictionaries) are collections that store data in key-value pairs. Each key is unique and maps to a specific value, making it easy to look up data quickly.

Creating Maps

Create a map by specifying the key and value types:
Map<String, int> edades = {
  'Juan'  : 17,
  'María' : 16,
  'Carlos': 18,
};
The syntax Map<String, int> means keys are Strings and values are integers. You can use any type for both keys and values.

Accessing Values

Access values using the key in square brackets:
print(edades['Juan']);  // 17
print(edades['María']); // 16
print(edades['Maria']); // null
Accessing a non-existent key returns null, not an error. Always check if a key exists before using its value if you’re unsure.

Adding and Updating Values

Adding New Entries

Assign a value to a new key to add it to the map:
edades['Ana'] = 17;
print(edades); // {Juan: 17, María: 16, Carlos: 18, Ana: 17}

Updating Existing Entries

Assigning to an existing key updates its value:
edades['Ana'] = 167;
print(edades); // {Juan: 17, María: 16, Carlos: 18, Ana: 167}
There’s no difference in syntax between adding and updating - if the key exists, it updates; if not, it adds.

Checking for Keys and Values

Check if Key Exists

Use containsKey() to verify if a key is present:
print(edades.containsKey('Juan')); // true

Check if Value Exists

Use containsValue() to check if any key has that value:
print(edades.containsValue(17)); // true
MethodDescriptionReturns
containsKey(key)Checks if the key existstrue or false
containsValue(value)Checks if any key has this valuetrue or false

Removing Entries

Use the remove() method to delete a key-value pair:
edades.remove('Carlos');
print(edades); // {Juan: 17, María: 16, Ana: 167}

edades.remove('Pedro'); // No error if key doesn't exist
print(edades); // {Juan: 17, María: 16, Ana: 167}
The remove() method doesn’t throw an error if the key doesn’t exist - it simply does nothing.

Map Properties

Maps provide several useful properties:

Get All Keys

print(edades.keys); // (Juan, María, Ana)

Get All Values

print(edades.values); // (17, 16, 167)

Get Number of Entries

print(edades.length); // 3

Check if Empty

print(edades.isEmpty); // false

Common Map Properties

PropertyDescriptionExample
keysReturns all keysedades.keys
valuesReturns all valuesedades.values
lengthNumber of key-value pairsedades.length
isEmptyReturns true if map is emptyedades.isEmpty
isNotEmptyReturns true if map has entriesedades.isNotEmpty

Complete Example

void main() {
  Map<String, int> edades = {
    'Juan'  : 17,
    'María' : 16,
    'Carlos': 18,
  };

  // ACCEDER
  print(edades['Juan']);  // 17
  print(edades['María']); // 16
  print(edades['Maria']); // null

  // AGREGAR si no Existe
  edades['Ana'] = 17;
  //Sobreescribir si ya Existe
  edades['Ana'] = 167;
  print(edades);

  // VERIFICAR
  print(edades.containsKey('Juan')); // ¿Existe la clave?
  print(edades.containsValue(17));   // ¿Existe el valor?

  // ELIMINAR
  edades.remove('Carlos');
  print(edades);
  edades.remove('Pedro');
  print(edades);

  // CONSULTAR
  print(edades.keys);   // Todas las claves
  print(edades.values); // Todos los valores
  print(edades.length);    // Cantidad de pares
  print(edades.isEmpty);   // ¿Vacío?
  
}

When to Use Maps

Quick Lookups

Find data instantly using a unique identifier (like ID, name, or code)

Associations

Connect related data, like names to phone numbers or products to prices

Counting

Track occurrences or frequencies of items

Configuration

Store settings and preferences with named keys

Maps vs Lists

FeatureListMap
AccessBy numeric index (0, 1, 2…)By unique key (any type)
OrderMaintains insertion orderMaintains insertion order*
DuplicatesValues can repeatKeys must be unique, values can repeat
Use CaseOrdered collectionsKey-value associations
SpeedO(1) by indexO(1) by key
*Dart maps maintain insertion order, but this is an implementation detail. If order matters, consider using a List instead.

Best Practices

Check before accessing: Use containsKey() to avoid null values:
if (edades.containsKey('Pedro')) {
  print(edades['Pedro']);
} else {
  print('Pedro no está en el mapa');
}
Use descriptive keys: Choose meaningful key names that clearly represent the data:
// Good
Map<String, int> studentGrades = {'Alice': 95, 'Bob': 87};

// Avoid
Map<String, int> data = {'a': 95, 'b': 87};

Build docs developers (and LLMs) love