Issue
I have this function that works with List
:
List<List<String>> experience() async {
List<List<String>> totalExperience = [];
List<String> temp = []; //a temporary List
temp = ["a", "b"];
totalExperience.add(temp); //adding the temp List to the 2D List
print(totalExperience);
//here I intend to remove the 2 elements ("a", "b") from the temp List,
//so that it can be used again.
temp.clear();
temp = ["c", "d"]; //initialising the temp List with 2 new elements
totalExperience.add(temp);
print(totalExperience);
temp.clear();
temp = ["e", "f"];
totalExperience.add(temp);
print(totalExperience);
return totalExperience;
}
This is actual the output in the console:
[[a, b]]
[[], [c, d]]
[[], [], [e, f]]
As clear from the output, the previous 2 elements in the totalExperience
List got removed.
However, I expected the output of this code to be something like this:
[[a, b], [c, d], [e, f]]
I can not figure out what could be the possible error in this code.
Also I might have framed the question title wrong. Will update it as soon as I figure out the error. Thanks.
Solution
Every time clear your temp array which reference actually you added to your totalExperience array. That's why whenever you clear temp array and then clear also in reference which add in totalExperience array. You can just copy your temp when adding to the totalExperience array.
List<List<String>> experience() {
List<List<String>> totalExperience = [];
List<String> temp = []; //a temporary List
List<String> tempOrgi;
temp = ["a", "b"];
totalExperience.add([...temp]); //adding the temp List to the 2D List
print(totalExperience);
//here I intend to remove the 2 elements ("a", "b") from the temp List,
//so that it can be used again.
temp.clear();
temp = ["c", "d"]; //initialising the temp List with 2 new elements
totalExperience.add([...temp]);
print(totalExperience);
temp.clear();
temp = ["e", "f"];
totalExperience.add([...temp]);
print(totalExperience);
return totalExperience;
}
Answered By - Poran
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.