Search code examples
algorithmflutterdartasync-awaithashmap

How to update keys of map in dart


I have a simple map "objects" lets assume this :

{
ServoP180V1: {X: 100.0, Y: 0.0}, 
ServoP180V3: {X: 100.0, Y: 0.0}
ServoP180V5: {X: 100.0, Y: 0.0}
}

How I can sort the keys in such way that they will be in an order, like this:

{
ServoP180V1: {X: 100.0, Y: 0.0}, 
ServoP180V2: {X: 100.0, Y: 0.0}
ServoP180V3: {X: 100.0, Y: 0.0}
}

I tried this code but it has problems with returning null sometimes, not sure Im in right way

  sortObjects() {
    int i = 1;
    for (var key in objects.keys) {
      objects.update(
        key.substring(0, key.length - 1) + i.toString(),
        null,
      );
      i++;
    }
  }
The method 'call' was called on null.
Receiver: null
Tried calling: call()

also this way

  sortObjects() {
    int i = 1;
    objects.forEach((key, value) {
      objects.update(
        key.substring(0, key.length - 1) + i.toString(),
        (existingValue) => value,
        ifAbsent: () => value,
      );
      i++;
    });
  }

giving such an error

Exception: Concurrent modification during iteration: 

Thank you in advance !


Solution

  • So you are changing the key during the foearch loop, this is illegal. I would change the keys by generating another map and then replacing the old one. It is an answer.

    Map.update()

    Update method of the map only updates the content of the key and only if it exists, but does not change the key itself. I didn't find anything related to changing keys for maps at runtime.

    Map<String, dynamic> oldMap = {
      "ServoP180V1": {"X": 100.0, "Y": 0.0},
      "ServoP180V3": {"X": 100.0, "Y": 0.0},
      "ServoP180V5": {"X": 100.0, "Y": 0.0}
    };
    Map<String, dynamic> newMap = {};
    int i = 1;
    oldMap.keys.toList().forEach((key) {
      newMap.addAll({
        "${key.substring(0, key.length - 1)}$i":
            oldMap[key]
      });
      i++;
    });
    print(oldMap);
    print(newMap);
    

    result:

    {ServoP180V1: {X: 100.0, Y: 0.0}, ServoP180V3: {X: 100.0, Y: 0.0}, ServoP180V5: {X: 100.0, Y: 0.0}}
    {ServoP180V1: {X: 100.0, Y: 0.0}, ServoP180V2: {X: 100.0, Y: 0.0}, ServoP180V3: {X: 100.0, Y: 0.0}}