Reputation: 1147
I have two screens that I'm passing a list from one to the other. The list type is a custom object that has another list inside of it. On the second screen, a random item is removed from the sublist until there are no more, at which point the item containing the empty list is also removed. This happens until there are no more items in the top level list. The problem is, when the list is modified, the item stay gone. Entering the second screen will pass along an empty list.
This is how I'm making the list copy that is being passed forward:
_pushWordLists(List<WordList>.from(_selections.values));
_pushWordLists(List<WordList> wordLists) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => CardWidget(wordLists)
)
);
}
And this is how I'm modifying the list:
_loadNewWord() {
if (wordLists.length > 0) {
wordLists.shuffle();
final wordList = wordLists.first;
if (wordList.words.length > 0) {
wordList.words.shuffle();
var words = List<String>.from(wordList.words);
final word = words.first;
words.remove(word);
wordList.words = words;
setState(() {
_multiplier = wordList.multiplier;
_word = word;
});
} else {
wordLists.remove(wordList);
_loadNewWord();
}
} else {
_done();
}
}
I was told that making a copy would allow me to modify it's length and also keep the original list intact. How can I achieve this?
Upvotes: 0
Views: 896
Reputation: 1325
It seems like you operate original instances of WordList
, instead of copies.
In the first line of first sample:
List<WordList>.from(_selections.values)
will create a new list with same instances of WordList
, as _selection
. The list object itself is new, but it contains same WordLists as _selection
.
In the second sample
final wordList = wordLists.first;
takes an instance of WordList
from passed list (remember, this instance is also included in original _selection
) and
wordList.words = words;
updates it.
Solution: line List<WordList>.from(_selections.values)
should be replaces with something to actually create a new list of actual clones of WordLists in _selection
. Importing dart:convert
and using JSON.decode(JSON.encode(object))
will not work in Flutter. So, you, most likely, have to come with own cloneFrom(WordList source)
method.
Upvotes: 1