flutterdarthashmaplinkedhashmap

Limit number of MapEntries in Map: Dart


I need to have a Map that stores exactly 100 key-value pairs.
If, while adding a new pair, the number of pairs exceeds 100, I want the oldest pair to be deleted and latest one added in.

Somewhat like a Queue with only 100 slots.

This is the current map,

Map<String, String> r = {
   rId: DateTime.now().toString() // Id is key, created time is value
}

I believe we can achieve this with some implementation of LinkedHashMap.
I do not understand how. Any help is appreciated


Solution

  • If you don't mind adding a package quiver has a LruMap which is exactly what you are describing. See its docs here.

    LRU stands for Least recently used so the items will be evicted from the map as you describe.