Introduction of Dart Collections
Dart collections are powerful data structures that store and manage multiple items in a single object. Collections are essential for any application, as they allow developers to handle data sets efficiently. Dart provides a variety of collection types, each suited to different uses. Here’s a detailed overview of the main types of collections in Dart, including lists, sets, and maps, along with examples of how to use them.
1. List
A List is an ordered group of objects. The elements of a List can be accessed using an index.
List<String> colors = ['red', 'green', 'blue']; print(colors[0]); // Output: red colors.add('yellow'); print(colors); // Output: [red, green, blue, yellow]
2. Set
A Set is a collection of unique items that cannot contain duplicates. It’s useful when you need to ensure that an item appears only once in a collection.
Set<String> names = {'Alice', 'Bob', 'Charlie'}; bool added = names.add('Alice'); // Returns false, Alice is already in the set print(names); // Output: {Alice, Bob, Charlie}
3. Map
A Map is a collection of key-value pairs, where each key must be unique. Maps are perfect for associating items with an identifier.
Map<String, int> phoneNumbers = { 'Alice': 123456, 'Bob': 234567, 'Charlie': 345678 }; print(phoneNumbers['Alice']); // Output: 123456 phoneNumbers['Dave'] = 456789; // Adds a new entry
4. Queue
A Queue is a collection that can be manipulated at both ends. You can add and remove items from the beginning or the end. This structure is not built-in and requires importing from dart:collection.
import 'dart:collection'; Queue<int> queue = Queue(); queue.addAll([1, 2, 3]); queue.addFirst(0); queue.addLast(4); print(queue); // Output: [0, 1, 2, 3, 4]
5. Iterable
The Iterable is the base class for all collection types in Dart. It provides methods to iterate and modify collections.
Iterable<int> numbers = [1, 2, 3]; Iterable<int> doubled = numbers.map((number) => number * 2); print(doubled.toList()); // Output: [2, 4, 6]
Conclusion of Dart Collections
Dart collections are integral to data management within applications. Each type provides unique benefits, allowing developers to choose the best tool for their data handling needs. Mastery of these collections enhances the functionality and performance of Flutter apps.
Thank for visiting Hybrid App Development
Posted by Hussam HM