Dart Collections: Data Management with List, HashSet and HashMap
My Introduction to Collections - Data Structures
Today I dove into Dart's data structures (Collections). List, HashSet and HashMap. At first I thought "aren't these all the same thing" but each has its own specific use cases.
Live Demo: Dart Collections Examples
Try List, HashSet and HashMap usage interactively:
List - Classic Arrays
Lists are the data structure we know best. Similar to arrays in other languages. Each element has an index (starting from 0) and works in order.
My First List Experiments
void main() {
List<int> numbers = [3, 4, 5];
List<String> names = ["Ahmet", "Mehmet", "Selda"];
List<double> ratios = [3.2, 3.3, 3.5];
print(numbers); // [3, 4, 5]
print(names); // [Ahmet, Mehmet, Selda]
print(ratios); // [3.2, 3.3, 3.5]
}Adding and Removing Data
// Adding
numbers.add(32);
names.add("New name");
ratios.add(3.4);
// Insert at specific position
numbers.insert(0, 100); // Adds to beginning
// Update
numbers[0] = 50; // Change first element
// Remove
numbers.remove(50); // Remove by value
numbers.removeAt(0); // Remove by indexAccessing Elements
print(numbers[0]); // First element
print(numbers.first); // First element
print(numbers.last); // Last element
print(numbers.length); // Number of elements
print(numbers.isEmpty); // Is it empty?
print(numbers.isNotEmpty); // Is it not empty?Useful List Methods
List<int> numbers = [5, 2, 8, 1, 9];
numbers.sort(); // Sort: [1, 2, 5, 8, 9]
numbers.reversed; // Reverse
numbers.contains(5); // Does it contain 5? true
numbers.indexOf(8); // Index of 8? 2
numbers.clear(); // Clear allHashSet - Unique Values
HashSet is a structure that doesn't allow duplicate values. If you try to add the same value twice, it only keeps one.
Why HashSet?
Imagine you're collecting user emails. You don't want the same email twice. HashSet is perfect for this.
import 'dart:collection';
void main() {
HashSet<String> emails = HashSet();
emails.add("[email protected]");
emails.add("[email protected]");
emails.add("[email protected]"); // Won't be added, already exists
print(emails); // {[email protected], [email protected]}
print(emails.length); // 2
}HashSet Features
HashSet<int> numbers = HashSet();
numbers.add(5);
numbers.add(3);
numbers.add(5); // Won't be added
print(numbers.contains(3)); // true
print(numbers.length); // 2
numbers.remove(3);
print(numbers); // {5}List vs HashSet
| Feature | List | HashSet |
|---|---|---|
| Duplicates | Allowed | Not allowed |
| Order | Maintains order | No guaranteed order |
| Access | By index | No index |
| Speed | Slower for search | Faster for search |
HashMap - Key-Value Pairs
HashMap stores data as key-value pairs. Like a dictionary: word (key) and its meaning (value).
First HashMap Example
void main() {
HashMap<String, int> ages = HashMap();
ages["Ahmet"] = 25;
ages["Mehmet"] = 30;
ages["Selda"] = 28;
print(ages["Ahmet"]); // 25
print(ages); // {Ahmet: 25, Mehmet: 30, Selda: 28}
}Practical Example: Product Prices
HashMap<String, double> prices = HashMap();
prices["Bread"] = 5.50;
prices["Milk"] = 12.00;
prices["Cheese"] = 45.00;
print("Bread price: ${prices["Bread"]} TL");
// Update
prices["Bread"] = 6.00;
// Check if exists
if (prices.containsKey("Milk")) {
print("Milk is available");
}
// Remove
prices.remove("Cheese");HashMap Methods
HashMap<String, int> scores = HashMap();
scores["Math"] = 85;
scores["Physics"] = 90;
scores["Chemistry"] = 78;
print(scores.keys); // Keys: (Math, Physics, Chemistry)
print(scores.values); // Values: (85, 90, 78)
print(scores.length); // 3
print(scores.isEmpty); // false
scores.clear(); // Clear allWhen to Use Which?
Use List:
- When order matters
- When you need to access by index
- When duplicates are allowed
- Shopping list, todo list, etc.
Use HashSet:
- When you need unique values
- When order doesn't matter
- When you need fast search
- Email list, unique IDs, tags, etc.
Use HashMap:
- When you need key-value pairs
- When you need to access by key
- Settings, translations, user info, etc.
Real Flutter Example
Product List with List
List<String> products = ["Apple", "Banana", "Orange"];
ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(products[index]),
);
},
)User Settings with HashMap
HashMap<String, bool> settings = HashMap();
settings["notifications"] = true;
settings["darkMode"] = false;
settings["autoSave"] = true;
SwitchListTile(
title: Text("Notifications"),
value: settings["notifications"] ?? false,
onChanged: (value) {
settings["notifications"] = value;
},
)What Did I Learn Today?
- List: Ordered, allows duplicates, access by index
- HashSet: Unique values, no guaranteed order, fast search
- HashMap: Key-value pairs, access by key
Tomorrow I'll look at try-catch and async-await topics. Error handling and asynchronous operations are very important in Flutter!
Learning Resources
- Dart's official documentation
- My own experimental code
- StackOverflow examples
I hope this article was useful. Feel free to comment if you have questions!
Contact: