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 isNotEmpty
Use isEmpty or isNotEmpty to check whether a list, set, or map has items or not.
Example:
void main() {
// Declaring an empty list of coffees
var coffees = [];
// Declaring a list of teas with some values
var teas = ['green', 'black', 'chamomile', 'earl grey'];
// Checking if the 'coffees' list is empty and printing the result
print(coffees.isEmpty); // Output: true (since the list is empty)
// Checking if the 'teas' list is not empty and printing the result
print(teas.isNotEmpty); // Output: true (since the list contains elements)
}
Output:
true
true
2. forEach()
To apply a function to each item in a list, set, or map, you can use forEach().
Example:
void main() {
// Declaring a list of tea types
var teas = ['green', 'black', 'chamomile', 'earl grey'];
// Using the map() function to convert each tea name to uppercase
var loudTeas = teas.map((tea) => tea.toUpperCase());
// Iterating over the modified list and printing each tea name
loudTeas.forEach(print); // Output: GREEN, BLACK, CHAMOMILE, EARL GREY
}
Output:
GREEN
BLACK
CHAMOMILE
EARL GREY
3.where()
- Use Iterable’s where() method to get all the items that match a condition.
- Use Iterable’s any() and every() methods to check whether some or all items match a condition.
Example:
void main() {
// Declaring a list of tea types
var teas = ['green', 'black', 'chamomile', 'earl grey'];
// Function to check if a tea is decaffeinated
// Chamomile is the only decaffeinated tea in this list.
bool isDecaffeinated(String teaName) => teaName == 'chamomile';
// Using any() to check if at least one tea in the list is decaffeinated.
print(teas.any(isDecaffeinated)); // Output: true (since chamomile is present)
// Using every() to check if all teas in the list are decaffeinated.
print(!teas.every(isDecaffeinated)); // Output: true (since not all teas are chamomile)
}
Output:
true
true
Conclusion
Utilizing these methods enhances the efficiency and manipulability of Dart collections. By understanding and applying iterable methods such as .isEmpty(), .forEach(), .where(), .any(), and .every(), developers can write cleaner and more efficient Dart code.