更新地图中的关键属性

Update key attribute in map

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

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

Class 条目如下所示:

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 != '');
}

我要做的是Entry('subpath', 'othercooltype').songs加1。我尝试了 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++
    }

您可以访问密钥并更改它的歌曲 属性 而无需更改地图。像这样:

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

并且您需要重写 Entry 相等运算符

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

@override
int get hashCode => super.hashCode;

Operator equals