Dart扩展Map以方便延迟加载

时间:2014-01-12 22:40:25

标签: class map dart extends

我正在尝试将服务器中的数据延迟加载到Map中 出于这个原因,我想为Map添​​加功能,以便当一个键不存在时,会调用以获取值

我试过的是:

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
}

这引发了一个错误,指出“无法解析隐式超级调用的构造函数Map”,这对我来说很神秘。

这是我第一次尝试扩展任何东西,所以我可能会做一些愚蠢的事情。 任何关于做得更好,或者可能告诉我使用不良做法的建议都将受到赞赏。

我已经研究过这个答案:How do I extend a List in Dart,但这是关于扩展List,而不是Map。我找了一个MapBase但找不到一个 我已经研究了这个答案:I want to add my own methods to a few Dart Classes,但这似乎是一个非常古老的答案,没有真正的解决方案。

亲切的问候, 亨德里克·扬

2 个答案:

答案 0 :(得分:4)

查看此post,您无法扩展Map及其子类。我认为获得你想要的最好方法就是实现它。

class LazyMap implements Map {
  Map _inner = {};

  operator [](key) => _inner.putIfAbsent(key, () => key.length);

  // forward all method to _inner
}

答案 1 :(得分:3)

您应该查看the other answer of How do I extend a List in Dart?;)在这个答案中,我指向DelegatingList。旁边有DelegatingMap

您可以使用DelegatingMap作为超类或mixin来执行您想要的操作:

import 'package:quiver/collection.dart';

class LazyMap extends DelegatingMap {
  final delegate = {};

  operator [](key) => putIfAbsent(key, () => key.length);
}

请注意,您将无法使用 xhr ,因为 xhr 是异步的。

相关问题