dictionarydartsplay-tree

Update key attribute in map


I have got a recursive SplayTreeMap (autogenerated) like this (pseudocode):

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

Class Entry looks like this:

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

What I want to do is to add 1 to Entry('subpath', 'othercooltype').songs. I tried map.update, but with no success ([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'). I also tried saving its value, removing the key and adding the updated key, but it was buggy (sometimes worked, sometimes not).

My current code:

    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++
    }

Solution

  • You could access the key and just change it's songs property without altering the map. Something like this:

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

    And you will need to override the Entry equality operator

    @override
    bool operator ==(other) {
      return this.path == other.path;
    }
    
    @override
    int get hashCode => super.hashCode;
    

    Operator equals