skip to Main Content

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


  1. You are trying to assign the return value of the shuffle method, which is a void. You should use the cascade notation instead.

    var doubledCards = List.from(availablePlaycards)..addAll(clonedCards)..shuffle();
    

    Now doubledCards has a type of List so its value can be used as an iterator in a for-in loop.

    This code is equivalent to:

    var doubledCards = List.from(availablePlaycards);
    doubledCards.addAll(clonedCards);
    doubledCards.shuffle();
    
    Login or Signup to reply.
  2. The issue is that shuffle() method doesn’t return a new list but shuffles the existing list in-place and returns void. Therefore, you are trying to iterate over void, 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:

    final List<Playcard> doubledCards = List.from(availablePlaycards)..addAll(clonedCards);
    doubledCards.shuffle();
    
    // Now you can use doubledCards in your loop
    for (final playcard in doubledCards) {
      // Your code here
    }
    

    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 of var or final if you want to correctly specify the type of the list elements. This can prevent potential issues and make your code more readable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search