Collections are groups of objects that represent a particular element. The dart::collection library is used to implement the Collection in Dart. There are a variety of collections available in Dart.
Dart Collection
There are 5 Interfaces that we have in the Dart Collection, as mentioned below:
- List
- Queue
- Set
- Map
- LinkedList

1. List Interface
The list is an ordered group of objects where each object is from one specific type. To define a list in Dart, specify the object type inside the angled brackets (<>).
Syntax:
List<String> fruits = ["Mango", "Apple", "Banana"]
Example:
Here, we have defined a list and performed some common operations along with some basic, commonly used methods.
Dart
void main() {
// creating a new empty List
List geekList = [];
// Adding an element to the geekList
geekList.addAll([1, 2, 3, 4, 5, "Apple"]);
print(geekList);
// Looping over the list
for (var i = 0; i < geekList.length; i++) {
print("element $i is ${geekList[i]}");
}
// Removing an element from geekList by index
geekList.removeAt(2);
// Removing an element from geekList by object
geekList.remove("Apple");
print(geekList);
// Return a reversed version of the list
print(geekList.reversed);
// Checks if the list is empty
print(geekList.isEmpty);
// Gives the first element of the list
print(geekList.first);
// Reassigning the geekList and creating the
// elements using Iterable
geekList = Iterable<int>.generate(10).toList();
print(geekList);
}
Output:
[1, 2, 3, 4, 5, Apple]
element 0 is 1
element 1 is 2
element 2 is 3
element 3 is 4
element 4 is 5
element 5 is Apple
[1, 2, 4, 5]
(5, 4, 2, 1)
false
1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Classes Associated with List Interface
Class | Description |
---|
UnmodifiableListView<E> | An unmodifiable List view of another List. |
2. Set Interface
Sets are one of the essential part of Dart Collections. A set is defined as an unordered collection of unique objects.
Syntax:
Set<String> fruits = {"Mango", "Apple", "Banana"};
Example:
As discussed earlier a set stores a group of objects that are not repeating. A sample program is shown below.
Dart
void main() {
// Initializing the Set and Adding the values
Set geekSet = new Set();
geekSet.addAll([9, 1, 2, 3, 4, 5, 6, 1, 1, 9]);
// Looping over the set
for (var el in geekSet) {
print(el);
}
// length of the set.
print('Length: ${geekSet.length}');
// printing the first element in the set
print('First Element: ${geekSet.first}');
// Deleting an element not present. No Change
geekSet.remove(10);
// Deleting an element 9
geekSet.remove(9);
print(geekSet);
}
Output:
9
1
2
3
4
5
6
Length: 7
First Element: 9
{1, 2, 3, 4, 5, 6}
Classes Associated with Set Interfaces
Classes | Description |
---|
Set<E> | Collection of objects in which each of the objects occurs only once |
---|
HashSet<E> | Unordered set backed by a hash table |
---|
LinkedHashSet<E> | Ordered set that maintains insertion order |
---|
SplayTreeSet<E> | Automatically sorted set using a self-balancing binary search tree |
---|
UnmodifiableSetView<E> | Read-only view of a set |
---|
Hashset:
In the Dart programming language, a HashSet is a collection that stores a set of unique elements, where each element can be of any type. Here is an example of how to use a HashSet in Dart:
Dart
import 'dart:collection';
void main() {
// Create a new HashSet
var set = HashSet<String>();
// Add some elements to the set
set.add('apple');
set.add('banana');
set.add('cherry');
// Check if an element is in the set
print(set.contains('apple')); // Output: true
print(set.contains('pear')); // Output: false
// Iterate over the set
set.forEach((element) {
print(element);
});
}
Output:
true
false
apple
banana
cherry
3. Map Interface
In Dart, Maps are unordered key-value pair collections that set an associate key to the values within. To define a Map, specify the key type and the value type inside the angle brackets(<>) as shown below:
Syntax:
Map<int, String> fruits = {1: "Mango", 2: "Apple", 3: "Banana"};
Example:
The map collection stores the objects as a key-value pair. An example is shown below.
Dart
void main() {
// Initializing the map with sample values.
var geekMap = {1: "Apple", 2: "Mango", 3: "Banana"};
print(geekMap);
// Adding elements by different methods.
geekMap.addAll({4: 'Pineapple', 2: 'Grapes'});
geekMap[9] = "Kiwi";
print(geekMap);
// printing key and values
print('Keys: ${geekMap.keys} \nValues: ${geekMap.values}');
// removing an element from the map by its key
geekMap.remove(2);
// printing the map and its length
print('{$geekMap} length is ${geekMap.length}');
}
Output:
{1: Apple, 2: Mango, 3: Banana}
{1: Apple, 2: Grapes, 3: Banana, 4: Pineapple, 9: Kiwi}
Keys: (1, 2, 3, 4, 9)
Values: (Apple, Grapes, Banana, Pineapple, Kiwi)
{{1: Apple, 3: Banana, 4: Pineapple, 9: Kiwi}} length is 4
Classes Associated with Map Interfaces
Classes | Description |
---|
MapBase<K, V> | This is the base class for Map |
HashMap<K, V> | Unordered key-value store |
LinkedHashMap<K, V> | Maintains insertion order |
SplayTreeMap<K, V> | Sorted map based on keys |
UnmodifiableMapBase<K, V> | Base class for read-only maps |
UnmodifiableMapView<K, V> | Read-only view of a map |
i. Hashmap
In the Dart programming language, a HashMap is a collection that stores key-value pairs, where the keys are unique and the values can be of any type. Here is an example of how to use a HashMap in Dart:
Dart
import 'dart:collection';
void main() {
// Create a new HashMap
var map = HashMap<int, String>();
// Add some key-value pairs to the map
map[1] = 'one';
map[2] = 'two';
map[3] = 'three';
// Access the value for a specific key
print(map[1]); // Output: one
// Iterate over the map
map.forEach((key, value) {
print('$key: $value');
});
}
Output:
one
1: one
2: two
3: three
4. Queue Interface
Queues are used to implement FIFO(First in First Out) collection. This collection can be manipulated from both ends.
Syntax:
import 'dart:collection';
Queue<String> queue = Queue.from(["Mango", "Apple", "Banana"]);
Example:
Dart
import 'dart:collection';
void main() {
// Initializing the Set and Adding the values
// We can also initialize a queue of a specific type
// as Queue<int> q = new Queue();
var geekQueue = new Queue();
geekQueue.addAll([9, 1, 2, 3, 4, 5, 6, 1, 1, 9]);
// Adds Element to the Start of the Queue
geekQueue.addFirst("GFG");
// Adds Element to the End of the Queue
geekQueue.addLast("GFG2");
print(geekQueue);
// Removes the first Element
geekQueue.removeFirst();
print(geekQueue);
// Removes the Last Element
geekQueue.removeLast();
print(geekQueue);
// printing the first element in the set
print('First Element: ${geekQueue.first}');
// Looping over the set
for (var el in geekQueue) {
print(el);
}
// Other Operations
// length of the set.
print('Length: ${geekQueue.length}');
// Deleting an element not present. No Change
geekQueue.remove(10);
// Deleting an element 9
geekQueue.remove(2);
print(geekQueue);
}
Output:
{GFG, 9, 1, 2, 3, 4, 5, 6, 1, 1, 9, GFG2}
{9, 1, 2, 3, 4, 5, 6, 1, 1, 9, GFG2}
{9, 1, 2, 3, 4, 5, 6, 1, 1, 9}
First Element: 9
9
1
2
3
4
5
6
1
1
9
Length: 10
{9, 1, 3, 4, 5, 6, 1, 1, 9}
Classes Associated with the Queue Interface
Classes | Description |
---|
DoubleLinkedQueue<E> | Doubly-linked list based on the queue data structure. |
5. LinkedList Interface
It is a specialized, double-linked list of elements. This allows const time adding and removing at the either end also the time to increase the size is constant.
Syntax:
class MyEntry extends LinkedListEntry<MyEntry> {
final String value;
MyEntry(this.value);
}
LinkedList<MyEntry> list = LinkedList<MyEntry>();
Example:
Below is the implementation of a Doubly Linked List in Dart:
Dart
// Dart Program to Implement
// Doubly Linked List
import 'dart:collection';
// Class that extends LinkedListEntry.
// Each item in the LinkedList will be
// an instance of this class.
base class Box extends LinkedListEntry<Box> {
final String contents;
final int number;
Box(this.contents, this.number);
}
void main() {
final myLinkedList = LinkedList<Box>();
// Adding elements to the LinkedList
myLinkedList.add(Box('First Box', 1));
myLinkedList.add(Box('Second Box', 2));
myLinkedList.add(Box('Third Box', 3));
// Iterating over the LinkedList
for (final box in myLinkedList) {
print(" ${box.contents} , ${box.number}");
}
// Remove an element from the LinkedList
final boxToRemove = myLinkedList.firstWhere(
(box) => box.contents == 'Second Box',
);
boxToRemove.unlink();
print('');
print('After removal:');
for (final box in myLinkedList) {
print(" ${box.contents} , ${box.number}");
}
}
Output:
First Box , 1
Second Box , 2
Third Box , 3
After removal:
First Box , 1
Third Box , 3
Classes Associated with LinkedList Interface
Class | Description |
---|
LinkedListEntry<E extends LinkedListEntry<E>> | An element of a LinkedList. |
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
8 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
3 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:D
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 needs
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
3 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: Dart// main function start void main() { // initialise a string String st = "GEEKSFORGEEKS"; // print the stri
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:Dart// main function start void main() { // initialise a st
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