Dart扩展了Map以方便延迟加载 [英] Dart extends Map to facilitate lazy loading
问题描述
我正尝试将服务器中的数据延迟加载到Map中。
出于这个原因,我想向Map添加功能,以便在不存在密钥时,
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.
我尝试过的是这样:
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.
我已经研究了这个答案:< a href = https://stackoverflow.com/questions/16247045>如何在Dart中扩展列表,但这只是扩展列表而不是地图。我一直在寻找MapBase,但找不到它。
我已经调查了这个答案:我想将我自己的方法添加到一些Dart类中,但这似乎是一个很老的答案,没有实际解决方案。
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.
亲切的问候,
Hendrik Jan
Kind regards, Hendrik Jan
推荐答案
查看此发布,您将无法扩展Map及其子类。我认为获得所需内容的最佳方法是实施它。
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
}
这篇关于Dart扩展了Map以方便延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!