Open In App

Dart Programming – Map

Last Updated : 25 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Dart programming, Maps are dictionary-like data types that exist in key-value form (known as lock-key). There is no restriction on the type of data that goes in a map data type. Maps are very flexible and can mutate their size based on the requirements.

However, it is important to note that all locks (keys) need to be unique inside a map data type. We can declare Map in two ways: 

  • Using Map Literals
  • Using Map Constructors

– Using Map Literals

A map can be declared using map literals as shown below:  

// Creating the Map using Map Literals
var map_name = { key1 : value1, key2 : value2, ..., key n : value n }


Example 1: Creating Map using Map Literals 

void main() {  
      
      // Creating Map using is literals
      var gfg = {'position1' : 'Geek',
                 'position2' : 'for',
                 'position3' : 'Geeks'};
      
      // Printing Its content
      print(gfg);
      
      // Printing Specific Content
      // Key is defined
      print(gfg['position1']); 
      
      // Key is not defined
      print(gfg[0]); 
}


Output: 

{position1: Geek, position2: for, position3: Geeks}
Geek
null


Example 2: 

void main() {  
      
      // Creating Map using is literals
      var gfg = {'position1' : 'Geek' 'for' 'Geeks'};
      
      // Printing Its content
      print(gfg);
      
      // Printing Specific Content
      // Key is defined
      print(gfg['position1']); 
}


Output: 

{position1: GeekforGeeks}
GeekforGeeks

You have noticed that different strings get concatenated to one.


Example 3: Inserting a new value into Map 

void main() {  
      
      // Creating Map
      var gfg = {'position1' : 'Geeks' 'for'  'Geeks'};
      
      // Printing Its content before insertion
      print(gfg);
      
      // Inserting a new value in Map
      gfg ['position0'] = 'Welcome to ';
      
      // Printing Its content after insertion
      print(gfg);
      
      // Printing Specific Content
      // Keys is defined
      print(gfg['position0'] + gfg['position1']); 
}


Output: 

{position1: GeeksforGeeks}
{position1: GeeksforGeeks, position0: Welcome to }
Welcome to GeeksforGeeks


– Using Map Constructors

// Creating the Map using Map Constructor
var map_name = new Map();

// Assigning value and key inside Map
map_name [ key ] = value;


Example 1: Creating Map using Map Constructors 

void main() {  
      
      // Creating Map using Constructors
      var gfg = new Map();
      
      // Inserting values into Map
      gfg [0] = 'Geeks';
      gfg [1] = 'for';
      gfg [2] = 'Geeks';
      
      // Printing Its content
      print(gfg);
      
      // Printing Specific Content
      // Key is defined
      print(gfg[0]); 
}


Output:  

{0: Geeks, 1: for, 2: Geeks}
Geeks


Example 2: Assigning same key to different element 

void main() {  
      
      // Creating Map using Constructors
      var gfg = new Map();
      
      // Inserting values into Map
      gfg [0] = 'Geeks';
      gfg [0] = 'for';
      gfg [0] = 'Geeks';
      
      // Printing Its content
      print(gfg);
      
      // Printing Specific Content
      // Key is defined
      print(gfg[0]); 
}


Output:  

{0: Geeks}
Geeks

You have noticed that the other two values were simply ignored.

Properties of Set in Dart

Property

Description

length

Returns the number of elements in the set

isEmpty

Returns true if the set contains no elements

isNotEmpty

Returns true if the set contains at least one element

first

Returns the first element of the set. Throws an error if the set is empty

last

Returns the last element of the set. Throws an error if the set is empty

single

Returns the only element of the set. Throws an error if the set is empty or contains more than one element

Implementation of Properties:

void main() {
      
      // Example Set with multiple elements
      Set<int> numbers = {10, 20, 30, 40, 50};
      
      // Example Set with a single element
      Set<int> singleElementSet = {100};
      
      // Example Empty Set
      Set<int> emptySet = {};
    
      // Demonstrating the properties
      print("Set: $numbers");
      print("Length: ${numbers.length}"); // Returns number of elements
      print("Is Empty: ${numbers.isEmpty}"); // Returns false
      print("Is Not Empty: ${numbers.isNotEmpty}"); // Returns true
      print("First Element: ${numbers.first}"); // Returns first element
      print("Last Element: ${numbers.last}"); // Returns last element
      
      // Handling single property
      print("Single Element Set: $singleElementSet");
      print("Single Element: ${singleElementSet.single}"); // Returns the only element
      
      // Handling an empty set
      print("Empty Set: $emptySet");
      print("Is Empty: ${emptySet.isEmpty}"); // Returns true
      
      try {
        // Throws error
        print("First Element of Empty Set: ${emptySet.first}"); 
      } 
      catch (e) {
        print("Error: Cannot access first element of an empty set.");
      }
      
      try {
        // Throws error
        print("Last Element of Empty Set: ${emptySet.last}"); 
      } 
      catch (e) {
        print("Error: Cannot access last element of an empty set.");
      }
      
      try {
        // Throws error
        print("Single Element of Empty Set: ${emptySet.single}"); 
      } 
      catch (e) {
        print("Error: Cannot get single element from an empty set.");
      }
      
      // Handling a Set with multiple elements
      // in single property
      try {
        // Throws error
        print("Single Element of Multiple Elements Set: ${numbers.single}"); 
      } 
      catch (e) {
        print("Error: Cannot get single element from a set with multiple elements.");
      }
}


Output:

Set: {10, 20, 30, 40, 50}
Length: 5
Is Empty: false
Is Not Empty: true
First Element: 10
Last Element: 50
Single Element Set: {100}
Single Element: 100
Empty Set: {}
Is Empty: true
Error: Cannot access first element of an empty set.
Error: Cannot access last element of an empty set.
Error: Cannot get single element from an empty set.
Error: Cannot get single element from a set with multiple elements.


Methods of Numbers in Dart

Method

Description

add(element)

Adds an element to the set and returns true if the element was successfully added

addAll(iterable)

Adds multiple elements to the set from the provided iterable

remove(element)

Removes the specified element from the set and returns true if the element was present

removeAll(iterable)

Removes all elements that exist in the specified iterable from the set

clear()

Removes all elements from the set.

contains(element)

Returns true if the set contains the specified element

containsAll(iterable)

Returns true if all elements in the provided iterable are present in the set

forEach(action)

Iterates through each element in the set and applies the given function

elementAt(index)

Returns the element at the specified index in the set. Throws an error if the index is out of range

toList()

Converts the set into a list

toSet()

Returns a new set containing the same elements as the current set

union(otherSet)

Returns a new set that contains all unique elements from both sets

intersection(otherSet)

Returns a new set containing only the elements found in both sets

difference(otherSet)

Returns a new set containing elements that are in the first set but not in the second set

retainWhere(test)

Removes all elements that do not satisfy the specified condition

removeWhere(test)

Removes all elements that satisfy the specified condition

lookup(object)

Returns the object from the set that matches the given object, or null if not found

Implementation of methods :

void main() {
      Set<int> numbers = {1, 2, 3, 4, 5};
    
      // add(element)
      print(numbers.add(6)); 
      // true
      
      // addAll(iterable)
      numbers.addAll({7, 8, 9});
      print(numbers);
    
      // remove(element)
      print(numbers.remove(3)); 
      // true
      
      print(numbers);
    
      // removeAll(iterable)
      numbers.removeAll({4, 5});
      print(numbers);
    
      // clear()
      numbers.clear();
      
      print(numbers); 
      // {}
    
      numbers = {10, 20, 30, 40, 50};
    
      // contains(element)
      print(numbers.contains(20)); 
      // true
    
      // containsAll(iterable)
      print(numbers.containsAll({20, 30})); 
      // true
    
      // forEach(action)
      numbers.forEach((num) => print(num * 2));
    
      // elementAt(index)
      print(numbers.elementAt(2)); 
      // 30
    
      // toList()
      List<int> numList = numbers.toList();
      print(numList);
    
      // toSet()
      Set<int> numSet = numList.toSet();
      print(numSet);
    
      Set<int> setA = {1, 2, 3, 4};
      Set<int> setB = {3, 4, 5, 6};
    
      // union(otherSet)
      print(setA.union(setB)); 
      // {1, 2, 3, 4, 5, 6}
    
      // intersection(otherSet)
      print(setA.intersection(setB)); 
      // {3, 4}
    
      // difference(otherSet)
      print(setA.difference(setB)); 
      // {1, 2}
    
      // retainWhere(test)
      setA.retainWhere((num) => num.isEven);
      
      print(setA); 
      // {2, 4}
    
      setA = {1, 2, 3, 4, 5};
    
      // removeWhere(test)
      setA.removeWhere((num) => num.isOdd);
      
      print(setA); 
      // {2, 4}
    
      // lookup(object)
      print(setB.lookup(3)); 
      // 3
      
      print(setB.lookup(10)); 
      // null
}


Output:

true
{1, 2, 3, 4, 5, 6, 7, 8, 9}
true
{1, 2, 4, 5, 6, 7, 8, 9}
{1, 2, 6, 7, 8, 9}
{}
true
true
20
40
60
80
100
30
[10, 20, 30, 40, 50]
{10, 20, 30, 40, 50}
{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{2, 4}
{2, 4}
3
null

Conclusion

In Dart, Maps and Sets are fundamental data structures that offer efficient ways to store and manipulate collections of data.

  • Maps operate as key-value pairs, allowing for flexible data storage where each key must be unique. They can be declared using map literals or map constructors, enabling dynamic and structured data management.
  • Sets, on the other hand, ensure that all stored elements are unique and provide various methods and properties to efficiently modify and retrieve elements.

By understanding these data structures and their operations, developers can optimize data handling, leading to improved performance and maintainability in Dart applications.



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg