Dart扩展了Map以方便延迟加载

Hen*_*Jan 3 extends class map dart

我正在尝试将数据从服务器延迟加载到Map中。
因此,我想向Map添加功能,以便在不存在键时进行调用以获取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
}
Run Code Online (Sandbox Code Playgroud)

这引起了一个错误,指出“无法为隐式超级调用解析构造函数映射”,这对我来说是一个神秘的问题。

这是我第一次尝试扩展任何内容,因此我可能会做一些愚蠢的事情。任何关于做得更好的建议,或者可能告诉我我使用的是不好的做法,将不胜感激。

我研究了这个答案:如何在Dart中扩展List,但这是关于扩展List而不是Map的。我一直在寻找MapBase,但是找不到。
我已经研究了这个答案:我想将自己的方法添加到一些Dart类中,但这似乎是一个很老的答案,没有真正的解决方案。

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

Ale*_*uin 6

您应该查看如何在 Dart 中扩展列表的另一个答案;) 在这个答案中,我指向DelegatingList。旁边是DelegatingMap

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

import 'package:quiver/collection.dart';

class LazyMap extends DelegatingMap {
  final delegate = {};

  operator [](key) => putIfAbsent(key, () => key.length);
}
Run Code Online (Sandbox Code Playgroud)

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


Far*_*ion 5

看这篇文章,您不能扩展Map及其子类。我认为获得所需的最佳方法是实施它。

class LazyMap implements Map {
  Map _inner = {};

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

  // forward all method to _inner
}
Run Code Online (Sandbox Code Playgroud)