dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.12k stars 1.57k forks source link

Very strange map behaviour #56656

Closed tanmay1100 closed 4 weeks ago

tanmay1100 commented 4 weeks ago

This is the relevant code:

 for (var map in allMaps +
              [
                intensity,
                generalMood,
                sleepQuality,
                energyLevel,
                exerciseIntensity
              ]) {
            // Collect the keys to remove and changes to apply after iteration

            List<MapEntry<dynamic, dynamic>> changes = [];
            List<dynamic> keysToRemove = [];

            map.forEach((key, value) {
              if (key == '') {
                changes.add(
                    MapEntry('No Data', value)); // Prepare to add new entry
                keysToRemove.add(key); // Mark key for removal
              }
            });

            // Remove the keys marked for deletion
            // for (var key in keysToRemove) {
            //   map.remove(key);
            // }

            // Apply the changes (add 'No Data' entries)
            map.addEntries(changes);
          }

This code, results in one of the maps being this:

{: 18, Decreased: 59,
Increased: 1, No Data: 18, 
Normal: 103}

Which is good. That's the intended result. But when i uncomment this snippet:

  // Remove the keys marked for deletion
            // for (var key in keysToRemove) {
            //   map.remove(key);
            // }

The map turns into this:

{Decreased: 59, Increased:
1, No Data: 1, Normal: 103}

When i was expecting:

{Decreased: 59, Increased:
1, No Data: 18, Normal: 103}

Why is this happening? When i remove the entry with the key set to the empty string, shouldn't it just remove that and be done? Why is it messing with the 'No Data' field?

dart-github-bot commented 4 weeks ago

Summary: The user is experiencing unexpected behavior when removing an empty string key from a map. The remove operation seems to be affecting other entries in the map, specifically the "No Data" entry, which is not expected.

mraleph commented 4 weeks ago

You will have to provide a runnable reproduction of the problem. It is not really possible to figure out what is going wrong just by looking at the snippet of the code.

If there is indeed a bug - it can be in many places.

tanmay1100 commented 4 weeks ago

Yeah going to look more into it on my end, pivoting to a different approach rn, will update with a runnable reproduction asap