Junior
Is there a collection that combines key uniqueness and insertion order preservation?
sobes.tech AI
Answer from AI
Yes, in Dart (and consequently in Flutter) there is a collection called LinkedHashMap, which combines the uniqueness of keys with preserving the order of insertion.
LinkedHashMap guarantees that when iterating over the keys, they will be returned in the order they were added, while keys remain unique.
Example of usage:
import 'dart:collection';
void main() {
var map = LinkedHashMap<String, int>();
map['apple'] = 1;
map['banana'] = 2;
map['orange'] = 3;
for (var key in map.keys) {
print('$key: ${map[key]}');
}
}
The output will be in insertion order: apple, banana, orange.