Introduction
In this blog, we will look into the Dart Collection Methods. We will discuss some of the common collection methods used to manipulate the elements of a list, string, or map. If you are new to Dart and are yet to set up your environment for the language, you can check out this article.
Dart Collection Methods
Before directly jumping on Collection methods, we suggest you take a quick overview of Dart Collections. Following are some of the common collection methods used to manipulate lists, strings, and maps:
sublist()
This method is used to slice a list. You can either specify the starting and ending index to get all the elements in that range. It will not take the element represented by the ending index. Only the elements in the range [starting_index, ending_index) will be returned. For example,
void main() {
var l = [2, 4, 6, 8, 10];
var sublist =l.sublist(1, 4); // all the elements having index in the range [1,4)
var sublist2 = l.sublist(2); // all the elements after the index 2
print(sublist);
print(sublist2);
}
Output:
[4, 6, 8]
[6, 8, 10]
shuffle()
This method is used to shuffle the elements of a list. For example,
void main() {
var l = [2, 4, 6, 8, 10];
l.shuffle(); // shuffling the elements of the list
print(l);
}
Output:
[2, 10, 8, 4, 6]
reversed
To reverse a list, this method is used. For example,
void main() {
var l = [2, 4, 6, 8, 10];
// reversing the list
var reversed_list = l.reversed.toList();
print(reversed_list);
}
Output:
[10, 8, 6, 4, 2]
asMap()
This method is used to convert a list into map. For example,
void main() {
var colors = ["red", "blue", "green"];
// getting map of the colors
var map_colors = colors.asMap();
// the key here would be the index of the element and the value would be the element itself.
print(map_colors);
}
Output:
{0: red, 1: blue, 2: green}
forEach()
You can use forEach() to apply a function to each element of a list, set, or map. For example,
void main() {
var l = [1, 2, 3, 4];
print("Following are the list items:");
// printing all the items of the list
l.forEach(print);
}
Output:
Following are the list items:
1
2
3
4
isEmpty
We utilise this method to check if a list is empty. It returns true if the list is empty.
// This program demonstrates the working of isEmpty method
void main() {
var l = [1, 2, 3, 4];
print("Is l empty?: " + l.isEmpty.toString());
}
Output:
Is l empty?: false
isNotEmpty
This method determines whether or not a list is empty. If the list contains some element, it returns true.
// This program demonstrates the working of isNotEmpty method
void main() {
var l = [1, 2, 3, 4];
print("Is l not empty?: " + l.isNotEmpty.toString());
}
Output:
Is l not empty?: true




