mrs.bassim
mrs.bassim

Reputation: 479

Adding values to LinkedHashMap results in the same value for all keys

I'm using a LinkedHashMap to add arrays to different keys, like below:

nextQ(String qid) {
print(answersList);
print(qid);
setState(() {
  answers[qid] = answersList;
});
print(answers);
_swipeAnimation();
answersList.clear();
}


clicked(String quesid, String id) {
setState(() {
  if (!answersList.contains(id)){
    answersList.add(id);
  }
  qid = quesid;
});
}

The first time nextQ is called I got:

answersList = [5c2c9b21108d3d04531494a7, 5c2c9b21108d3d04531494a6]

and the answers = {5c2c9b21108d3d04531494a4: [5c2c9b21108d3d04531494a7, 5c2c9b21108d3d04531494a6]}

which is correct. The second time it's called I got:

answersList = [5c2c9b21108d3d04531494a2] .. which is correct

and the answers are:

answers = {5c2c9b21108d3d04531494a4: [5c2c9b21108d3d04531494a2], 5c2c9b21108d3d04531494a1: [5c2c9b21108d3d04531494a2]}

which is wrong. Why is the last answersList value set for all keys in the map?

Upvotes: 1

Views: 814

Answers (1)

user
user

Reputation: 87064

You use the same list(answersList) every time you set an entry in the map, so this list becomes the backing list for all values in your map. So every change you make to the answersList will be replicated to all values in the map. You could see this if you put a print statement after the answersList.clear(); line, this will print your map with the ids pointing to empty lists.

To fix this you need to create a copy of the answersList for each value that will be put in the map:

answers[qid] = List.from(answersList);

Upvotes: 0

Related Questions