Dart extends Map to facilitate lazy loading

半城伤御伤魂 提交于 2020-07-07 04:56:34

问题


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


回答1:


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
}



回答2:


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.



来源:https://stackoverflow.com/questions/21081210/dart-extends-map-to-facilitate-lazy-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!