NirG
NirG

Reputation: 71

Changing value in Map dose not change actual value in dart

In the fallowing code example, I created a class that maintains a Map with some values. The class has a "clear" method to clear the values in the map. However, calling the clear method dose not clear the actual values on the map.

Any ideas?

class CountStuff {
  Map<String, int> Records = Map();

  CountStuff() {
    Records['one'] = 10;
    Records['two'] = 20;
    Records['seven'] = 255;
    Records['moses'] = 349;
  }

  void clear() {
    Records.forEach((key, value) {
      value = 0;
    });
  }
}

void main() {
  CountStuff cs = CountStuff();

  cs.Records.forEach((key, value) {
    print(value);
  });

  cs.clear();

  cs.Records.forEach((key, value) {
    print(value);
  });
}

output is: flutter: 10

flutter: 20

flutter: 255

flutter: 349

flutter: 10

flutter: 20

flutter: 255

flutter: 349

Upvotes: 0

Views: 747

Answers (2)

apc
apc

Reputation: 1432

Your clear() function should look like this:

void clear() {
    Records.updateAll((key, value) => 0);
}

updateAll iterates through all map keys and updates values accordingly.

The accepted answer also works but it performs more than double work to find again the element by key although the element is already known by iterating.

Upvotes: 0

ChessMax
ChessMax

Reputation: 2265

In a foreach loop you do not modify the actual map, because you are working with a copy of the map values. It's not a reference or something. So this code:

Records.forEach((key, value) {
      value = 0;
    });

really does nothing. You need something like this:

Records.forEach((key, value) {
  Records[key] = 0;
});

Upvotes: 4

Related Questions