When working with Dart and Flutter, there might be cases where you want to count the occurrences of each element in a given list. The best strategy to get the job done is to use a map to store the frequency of each element in the list (use the list elements as keys and their counts as values). The next step is to loop over the list and update the map accordingly.
The simple example below will demonstrate how to do that in practice:
void main() {
// this list contains both strings and numbers
final List myList = [
'blue',
'red',
'amber',
'blue',
'green',
'orange',
'red',
'blue',
'pink',
'amber',
'blue',
123,
123,
234
];
// this map has keys and values that are the elements and their occurrences in the list, respectively
final Map counts = {};
// loop through the list
// If an element appears for the first time, set it to a key of the map and the corresponding value to 1
// If an element is already used to a key, its corresponding value is incremented by 1
myList.map((e) => counts.containsKey(e) ? counts[e]++ : counts[e] = 1);
// print out the result
print(counts);
}
Output:
{
blue: 4,
red: 2,
amber: 2,
green: 1,
orange: 1,
pink: 1,
123: 2,
234: 1
}
That’s it. Further reading:
- Dart: Extract a substring from a given string (advanced)
- Dart: Convert Class Instances (Objects) to Maps and Vice Versa
- How to implement a loading dialog in Flutter
- Environment Variables in Flutter: Development & Production
- Flutter & Hive Database: CRUD Example
- Dart & Flutter: Get the Index of a Specific Element in a List
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.