Design Converter
Education
Software Development Executive - II
Last updated on Sep 16, 2024
Last updated on Sep 16, 2024
Dart, a powerful indeed versatile programming language, that is used to manage groups of data effectively. Dart collections are key data structures in Dart that allow for easy collection traversal and efficient data manipulation, similar to collections in other programming languages. Especially significant for Flutter developers, understanding Dart collections can unlock powerful programming techniques for versatile Flutter apps.
There are four types of collections in Dart: List, Set, Queue, and Map. However, we will focus on the primary ones, List and Set and their close relation, Map.
In Dart, a collection is an ordered group of items, unlike unordered collections in some other programming languages. Typically, they can contain elements, each of which can hold either simple variables or complex objects. A user can perform different operations, such as inserting, deleting, or finding items in a collection.
The primary advantage is a more organized way of handling data, making the code cleaner and more manageable. Let's explore the types of collections in Dart.
Anyone who toys with the idea of Flutter invariably stumbles onto Dart sooner or later. That's because Dart is the programming language of choice for Flutter, mainly because of its excellent support for collection literals.
Collection literals in Dart can be used to define and create collections easily and quickly. It's the use case for these collection literals that makes Dart an ideal choice for Flutter.
The interactive code snippets below offer a glimpse of how Dart collections function. Note the void main function, which is obligatory in everyone Dart program.
1 void main() { 2 List<dynamic> grocery = ["Milk", "Bread", "Cheese"]; 3 print(grocery); 4 Map<String, int> scoreCard = {"Alice": 450, "Bob": 300}; 5 print(scoreCard); 6 Set<String> languages = {"C", "Java", "Python"}; 7 print(languages); 8 } 9
This example illustrates the practical utility of three types of dart collection: List, Map, and Set.
Just like setting up your toolkit before crafting a masterpiece, gaining knowledge about Dart collections lays a strong foundation for coding versatile Flutter apps.
Perhaps the most familiar of all, the List class represents lists in Dart which is a dynamic collection. A List can be defined as an ordered group of items. The List class in Dart, part of its core library, encompasses methods that assist you in managing and manipulating lists.
Lists can be classified into two categories: a fixed-length list, a list's length that doesn’t change, and a growable list that can change its length dynamically.
Here is how you can define a List:
1 void main() { 2 var list = [1, 2, 3]; 3 // list literal 4 print(list); 5 List <String> otherList = List(); 6 // list class 7 print(otherList); 8 } 9
This code defines a List in Dart, first using a List literal, then using the List class.
While Lists store an ordered group of items, a Set class represents an unordered collection of unique items. Similar to a List, a set can contain only one element of a specific value. It can be used when you want to make sure no duplicates are present.
Let's illustrate this with an example:
1 void main() { 2 var set = {'hello', 'world'}; 3 // set literal 4 print(set); 5 Set <String> anotherSet = Set(); 6 // set class 7 print(anotherSet); 8 } 9
This example demonstrates how to define a Set in Dart.
Maps in Dart are dynamic collections of key-value pairs. Each item in a Map has a key and a value associated with it. The Map class defines the operations for Maps.
Maps are written as a pair of keys and values in curly braces ({})
. You can create maps with the Map() constructor or directly using {}
.
Example of Map in Dart:
1 void main() { 2 var map = {'firstName': 'Alice', 'lastName': 'Johnson'}; 3 // map literal 4 print(map); 5 Map<String, int> anotherMap = Map(); 6 // map class 7 print(anotherMap); 8 } 9
This example shows the definition of a Map using the Map literal and the Map class.
Diving into Dart, we find that the dart:collection library is an essential part of the language. Collections are core components of any programming language, and Dart is no different. It comes with a rich core library which includes dart:collection, providing many functionalities that make handling Dart collections an enjoyable process.
The dart:collection library provides a wide variety of classes to manipulate and process collections more efficiently. It includes classes for lists, sets, maps, and queues and also offers several additional utilities.
The dart:collection library provides us with various tools for working with collections, like HashSet, LinkedHashMap, Queue, SplayTreeSet, and more. Among these tools, we will concentrate on a few of them:
These classes, among others, provide you with everything you need to handle Dart collections efficiently.
In the world of Dart collections, Iterable is a term that holds significant prominence. Iterable collections, like Lists and Sets, are collections of items that can be sequentially accessed.
Dart Iterable is a collection of values, or "elements", that can be accessed sequentially. An Iterable in Dart contains methods that can be used for iterating collections of items, like Lists and Sets.
Iterable collections in Dart are equipped with the Iterator property which allows simple iterative actions such as moving to the next item or returning to the current property.
The Iterator class defines a pointer-like object. The methods provided by Iterator enable you to navigate through the elements of a collection.
This can be seen in the following example:
1 void main() { 2 var list = [1, 2, 3]; 3 var i = list.iterator; 4 while(i.moveNext()) { 5 print(i.current); 6 } 7 } 8
In this code snippet, we are traversing through the list using the Iterator class.
With dart:collection, you can transform and filter objects in your collection. Iterable's where() function lets you filter items from your collection based on a condition and gives the output as an Iterable.
Look at this transformation in the code snippet below:
1 void main() { 2 var list = [1, 2, 3, 4, 5]; 3 var evenNumbers = list.where((num) => num%2 == 0); 4 print(evenNumbers); 5 } 6
Here, we are obtaining even numbers from a list of numbers using the where function.
Dart’s Iterable class offers several methods which can be helpful while iterating the collections, such as map(), reduce(), expand(), etc.
Now that we’ve familiarized ourselves with Dart collections, it's time to understand how they play a pivotal role in Flutter development.
Dart list maps are used profusely in Flutter, especially when dealing with a dynamic collection of widgets. For instance, let's say you want to generate a list of Text widgets dynamically. Here, a List Map becomes particularly handy.
An example of how dynamic lists can be built in Flutter:
1 void main() { 2 List<String> items = ['Item 1', 'Item 2', 'Item 3']; 3 Column column = Column( 4 children: items.map((item) => Text(item)).toList(), 5 ); 6 print(column); 7 } 8
In the above example, we are dynamically creating a list of Text widgets based on the values we have in the List of Strings.
While Dart Iterable is a remarkable feature, it shines excellently in Flutter applications. You can access various elements from an iterable easily, which is particularly useful for processing data inside widgets.
Here, we will look at an example of how you can use iterable collections in Flutter.
In some cases, you might receive a collection of data and need to display each datum as a widget. To do that, you need to convert the list to an Iterable first.
1 var myIterable = myList.map((item) => new Text(item)); 2
With Iterable, you can use tools such as map and reduce to easily apply a function on each item within your collection.
1 var myList = myIterable.toList(); 2
This simple conversion can make building dynamic lists in Flutter way easier and more efficient.
In this blog, we have embarked on a detailed journey, exploring the essentials of Dart collections. With the knowledge you have gained, you are better equipped to leverage the power of Dart collections in your Flutter development journey, making your apps more dynamic, efficient, and adaptable. Taking the deal with data structures like lists, sets, maps, and queues, we carefully treaded on Dart's broad arsenal for handling collections, the dart:collection library. We also witnessed the exciting world of Iterables in Dart and how it aids in easy collection traversal, especially significant in Flutter applications. But the journey doesn't end here. As a developer, the world of Dart and Flutter provides an exciting landscape of continual learning and exploration. So keep exploring and coding! 🚀
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.