PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] How to update keys of map in dart

 September 20, 2022     algorithm, async-await, dart, flutter, hashmap     No comments   

Issue

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


Answered By - Chance
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing