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
You should have looked at the other answer of How do I extend a List in Dart? ;) In this answer I point to DelegatingList. Next to it there's DelegatingMap.
You can use DelegatingMap as superclass or as mixin to do what you want :
import 'package:quiver/collection.dart';
class LazyMap extends DelegatingMap {
final delegate = {};
operator [](key) => putIfAbsent(key, () => key.length);
}
Note that you will not be able to use this with xhr because xhr is asynchronous.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With