更新地图中的关键属性

时间:2019-08-23 15:35:57

标签: dictionary dart splay-tree

我有一个这样的递归SplayTreeMap(自动生成)(伪代码):

SplayTreeMap map = <SplayTreeMap>{
  Entry('path', 'cooltype'): <SplayTreeMap>{
    Entry('subpath', 'othercooltype'): <SplayTreeMap>{
      Entry('subsubpath', 'coolcooltype'): <SplayTreeMap>{},
    },
    Entry('othersubpath', 'othercooltype'): <SplayTreeMap>{},
  },
}

Class Entry看起来像这样:

class Entry implements Comparable<Entry> {
  String path;
  String type = 'defaulttype';
  int songs = 0;

  Entry(this.path, this.type);

  @override
  int compareTo(Entry other) =>
      this.path.toLowerCase().compareTo(other.path.toLowerCase());

  @override
  String toString() => 'Entry( ${this.path} )';

  String get name => path.split('/').lastWhere((e) => e != '');
}

我想要做的是将1加到Entry('subpath', 'othercooltype').songs。我尝试了map.update,但没有成功([ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '(dynamic) => dynamic' is not a subtype of type '(SplayTreeMap<dynamic, dynamic>) => SplayTreeMap<dynamic, dynamic>' of 'update')。我还尝试保存其值,删除密钥并添加更新的密钥,但这是有问题的(有时可行,有时无效)。

我当前的代码:

    Entry entry = Entry(relativeString, type);
    if (type == 'othercooltype') entry.songs++;
    if (!submap.containsKey(entry)) {
      submap[entry] = SplayTreeMap();
      setState(() => valueChanged(value++));
    } else {
      // update key with songs++
    }

1 个答案:

答案 0 :(得分:1)

您可以访问该键,而无需更改地图即可更改它的歌曲属性。像这样:

Entry keyEntry = submap.keys.firstWhere((key) => key == entry);
keyEntry.songs = 1;

您将需要覆盖Entry equal操作符

@override
bool operator ==(other) {
  return this.path == other.path;
}

@override
int get hashCode => super.hashCode;

Operator equals