I want to clone an existing list, shuffle it and use it in a loop in a children. But when I use it I got an error.
If I use it like this:
const availablePlaycards = [
Playcard(front: 'back.png', back: 'sheep.png'),
Playcard(front: 'back.png', back: 'cow.png'),
Playcard(front: 'back.png', back: 'pig.png'),
];
var doubledCards = (List.from(availablePlaycards)..addAll(clonedCards)).shuffle();
I got here
children: [
for (final playcard in doubledCards)
the error:
A nullable expression can't be used as an iterator in a for-in loop.
and
This expression has a type of 'void' so its value can't be used.
I have added an exclamation mark:
for (final playcard in doubledCards!)
But the error persists.
I have also tries like this without shuffle().
final List doubledCards = (List.from(availablePlaycards)..addAll(clonedCards));
Then I do not get the error, but the cards are not shuffled.
If I add shuffle here:
for (final playcard in doubledCards.shuffle())
I got the error:
A nullable expression can't be used as an iterator in a for-in loop.
How can I use it with shuffle?
2
Answers
You are trying to assign the return value of the
shuffle
method, which is avoid
. You should use the cascade notation instead.Now
doubledCards
has a type ofList
so its value can be used as an iterator in a for-in loop.This code is equivalent to:
The issue is that
shuffle()
method doesn’t return a new list but shuffles the existing list in-place and returnsvoid
. Therefore, you are trying to iterate overvoid
, which is causing the error.To shuffle a copy of the list without modifying the original list, you should shuffle the copy after creating it. You can do something like this:
By doing this, you create a new list, add elements to it, and then shuffle the new list. This ensures that your original
availablePlaycards
list remains unchanged.Remember that you need to use
List<Playcard>
instead ofvar
orfinal
if you want to correctly specify the type of the list elements. This can prevent potential issues and make your code more readable.