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
Dart
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:
Dart
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
Dart
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
Dart
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
Dart
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:
Dart
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 :
Dart
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.
Similar Reads
Dart Tutorial
Dart is an open-source general-purpose programming language developed by Google. It supports application development on both the client and server side. However, it is widely used for the development of Android apps, iOS apps, IoT(Internet of Things), and web applications using the Flutter Framework
7 min read
Data Types
Dart - Data Types
Like other languages (C, C++, Java), whenever a variable is created, each variable has an associated data type. In Dart language, there are the types of values that can be represented and manipulated in a programming language. In this article, we will learn about Dart Programming Language Data Types
9 min read
Basics of Numbers in Dart
Like other languages, Dart Programming also supports numerical values as Number objects. The number in Dart Programming is the data type that is used to hold the numeric value. Dart numbers can be classified as: int (Integer) The int data type is used to represent whole numbers. Declaring Integer in
6 min read
Strings in Dart
A Dart string is a sequence of UTF-16 code units. With the same rule as that of Python, you can use either single or double quotes to create a string. The string starts with the datatype String or Var : String string = "I love GeeksforGeeks";var string1 = 'GeeksforGeeks is a great platform for upgra
6 min read
Dart - Sets
Sets in Dart is a special case in List, where all the inputs are unique i.e. it doesn't contain any repeated input. It can also be interpreted as an unordered array with unique inputs. The set comes into play when we want to store unique values in a single variable without considering the order of t
6 min read
Dart Programming - Map
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 l
7 min read
Queues in Dart
Dart also provides the user to manipulate a collection of data in the form of a queue. A queue is a FIFO (First In First Out) data structure where the element that is added first will be deleted first. It takes the data from one end and removes it from the other end. Queues are useful when you want
4 min read
Data Enumeration in Dart
Enumerated types (also known as enumerations or enums) are primarily used to define named constant values. The enum keyword is used to define an enumeration type in Dart. The use case of enumeration is to store finite data members under the same type definition. Declaring enumsenum variable_name{ //
3 min read
Key Functions
Dart - Anonymous Functions
An anonymous function in Dart is like a named function but they do not have names associated with it. An anonymous function can have zero or more parameters with optional type annotations. An anonymous function consists of self-contained blocks of code and that can be passed around in our code as a
2 min read
Dart - main() Function
The main() function is a predefined method in Dart. It is the most important and mandatory part of any dart program. Any dart script requires the main() method for its execution. This method acts as the entry point for any Dart application. It is responsible for executing all library functions, user
2 min read
Dart - Common Collection Methods
List, Set, and Map share common functionalities found in many collections. Some of this common functionality is defined by the Iterable class, which is implemented by both List and Set. 1. isEmpty() or isNotEmptyUse isEmpty or isNotEmpty to check whether a list, set, or map has items or not. Example
2 min read
How to Exit a Dart Application Unconditionally?
The exit() method exits the current program by terminating the running Dart VM. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination. This is a similar exit in C/C++, Java. This method doesn't wait for any asynchronous operations to term
2 min read
Dart - Getters and Setters
Getters and Setters, also called accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively. Getters or accessors are defined using the get keyword.Setters or mutators are defined using the set keyword.A default getter/setter is associated with every
3 min read
Dart - Classes And Objects
Dart is an object-oriented programming language, so it supports the concept of class, object, etc. In Dart, we can define classes and objects of our own. We use the class keyword to do so. Dart supports object-oriented programming features like classes and interfaces. Let us learn about Dart Classes
4 min read
Object-Oriented Programming
Dart - this keyword
this keyword represents an implicit object pointing to the current class object. It refers to the current instance of the class in a method or constructor. The this keyword is mainly used to eliminate the ambiguity between class attributes and parameters with the same name. When the class attributes
2 min read
Dart - Static Keyword
The static keyword is used for the memory management of global data members. The static keyword can be applied to the fields and methods of a class. The static variables and methods are part of the class instead of a specific instance. The static keyword is used for a class-level variable and method
3 min read
Dart - Super and This keyword
Super Keyword in DartIn Dart, the super keyword is used to refer immediate parent class object. It is used to call properties and methods of the superclass. It does not call the method, whereas when we create an instance of subclass than that of the parent class is created implicitly so super keywor
4 min read
Dart - Concept of Inheritance
In Dart, one class can inherit another class, i.e. dart can create a new class from an existing class. We make use of extend keyword to do so. Terminology: Parent Class: It is the class whose properties are inherited by the child class. It is also known as a base class or super class.Child Class: It
5 min read
Instance and class methods in Dart
Dart provides us with the ability to create methods of our own. The methods are created to perform certain actions in class. Methods help us to remove the complexity of the program. It must be noted that methods may or may not return any value, and also, they may or may not take any parameter as inp
3 min read
Method Overriding in Dart
Method overriding occurs in Dart when a child class tries to override the parent class's method. When a child class extends a parent class, it gets full access to the methods of the parent class and thus it overrides the methods of the parent class. It is achieved by re-defining the same method pres
3 min read
Getter and Setter Methods in Dart
Getter and Setter methods are class methods used to manipulate the data of class fields. Getter is used to read or get the data of the class field, whereas setter is used to set the data of the class field to some variable. The following diagram illustrates a Person class that includes: A private va
2 min read
Abstract Classes in Dart
An abstract class in Dart is defined as a class that contains one or more abstract methods (methods without implementation). To declare an abstract class, we use the abstract keyword. It's important to note that a class declared as abstract may or may not include abstract methods. However, if a clas
4 min read
Dart - Builder Class
In Flutter, each widget has an associated build method responsible for rendering the UI. The Flutter framework automatically provides a BuildContext parameter to the build method. Widget build ( BuildContext context )Flutter takes care that there need not be any Widget apart from the build that need
4 min read
Concept of Callable Classes in Dart
Dart allows the user to create a callable class which allows the instance of the class to be called as a function. To allow an instance of your Dart class to be called like a function, implement the call() method. Syntax : class class_name { ... // class content return_type call ( parameters ) { ...
4 min read
Interface in Dart
The interface in the dart provides the user with the blueprint of the class, which any class should follow if it interfaces that class, i.e., if a class inherits another, it should redefine each function present inside an interfaced class in its way. They are nothing but a set of methods defined for
3 min read
Dart - extends Vs with Vs implements
All developers working with Dart for application development using the Flutter framework regularly encounter different usages of the implements, extends, and keywords. In Dart, one class can inherit another class, i.e. , Dart can create a new class from an existing class. We make use of keywords to
4 min read
Dart - Date and Time
A DateTime object is a point in time. The time zone is either UTC or the local time zone. Accurate date-time handling is required in almost every data context. Dart has the marvelous built-in classes for date time and duration in dart:core. Key Uses of DateTime in Dart:Comparing and Calculating Date
4 min read
Using await async in Dart
The async and await approaches in Dart are very similar to other languages, which makes it a comfortable topic to grasp for those who have used this pattern before. However, even if you donât have experience with asynchronous programming using async/await, you should find it easy to follow along her
4 min read
Dart Programs
Dart - Sort a List
The List data type is similar to arrays in other programming languages. A list is used to represent a collection of objects. It is an ordered group of objects. The core libraries in Dart are responsible for the existence of the List class, its creation, and manipulation. Sorting of the list depends
2 min read
Dart - String toUpperCase() Function with Examples
The string toUpperCase() method converts all characters of the string into an uppercase letter. The string toUpperCase() function returns the string after converting all characters of the string into the uppercase letter. Syntax: Str.toUpperCase()Parameter: The string toUpperCase() function doesn't
1 min read
Dart - Convert All Characters of a String in Lowercase
With the help of the toLowerCase() method in the string will convert all the characters in a string in lowercase. Syntax: String.toLowerCase() Return: string Image Representation: Example 1: [GFGTABS] Dart // main function start void main() { // initialise a string String st = "GEEKSFORGEEKS
1 min read
How to Replace a Substring of a String in Dart?
To replace all the substrings of a string, we make use of the replaceAll method in Dart. This method replaces all the substrings in the given string with the desired substring. Returns a new string in which the non-overlapping substrings matching from (the ones iterated by from.allMatches(this Strin
2 min read
How to Check String is Empty or Not in Dart (Null Safety)?
We can check a string is empty or not by the String Property isEmpty. If the string is empty then it returns True if the string is not empty then it returns False. Syntax: String.isEmpty Return : True or False.Image Representation: Example 1: [GFGTABS] Dart // main function start void main() { // in
1 min read
Exception Handling in Dart
An exception is an error that occurs inside the program. When an exception occurs inside a program, the normal flow of the program is disrupted, and it terminates abnormally, displaying the error and exception stack as output. So, an exception must be taken care of to prevent the application from te
3 min read
Assert Statements in Dart
As a programmer, it is very necessary to make an errorless code is very necessary and to find the error is very difficult in a big program. Dart provides the programmer with assert statements to check for the error. The assert statement is a useful tool to debug the code, and it uses a Boolean condi
3 min read
Fallthrough Condition in Dart
Fall through is a type of error that occurs in various programming languages like C, C++, Java, Dart ...etc. It occurs in switch-case statements where when we forget to add break statement and in that case flow of control jumps to the next line. "If no break appears, the flow of control will fall th
3 min read
Concept of Isolates in Dart
Dart was traditionally designed to create single-page applications. We also know that most computers, even mobile platforms, have multi-core CPUs. To take advantage of all those cores, developers traditionally use shared-memory threads running concurrently. However, shared-state concurrency is error
2 min read