Search code examples
classdictionarydartextends

Dart extends Map to facilitate lazy loading


I am trying to lazy-load data from the server into a Map.
For that reason I would like to add functionality to Map, so that when a key doesn't exist, a call is done to get the value.

What I tried is this:

class LazyMap extends Map {
  // use .length for now. When this works, go use xhr
  operator [](key) => LazyMap.putIfAbsent(key, () => key.length);
}

LazyMap test = new LazyMap();

main() {
  print(test.containsKey('hallo')); // false

  // I prefer to use this terse syntax and not have to use putIfAbsent
  // every time I need something from my map
  print(test['hello']); // 5

  print(test.containsKey('hallo')); // true
}

This raises an error stating "Cannot resolve constructor Map for implicit super call" which is cryptic for me.

This is the first time I try to extend anything, so I might be doing stupid things. Any advise on doing this better, or probably telling me that I am using a bad practice will be appreciated.

I've looked into this answer: How do I extend a List in Dart, but this is about extending a List, not a Map. I've looked for a MapBase but could not find one.
And I've looked into this answer: I want to add my own methods to a few Dart Classes, but this seems to be a very old answer with no real solution.

Kind regards, Hendrik Jan


Solution

  • Looking at this post, you cannot extends Map and its subclass. I think the best way to get what you want is to implement it.

    class LazyMap implements Map {
      Map _inner = {};
    
      operator [](key) => _inner.putIfAbsent(key, () => key.length);
    
      // forward all method to _inner
    }