Why can't I assign a shuffled array to a new array
Why can't I assign a shuffled array to a new array?
For example, this is my list:
List nums = [1, 2, 3];
List newlist=nums.shuffle();
However, this does not work for me.
Solution 1:
Because shuffle()
on List
does not return anything (which is indicated by void
which means the method does not return anything usable) but are instead shuffling the list you are calling the method on.
void shuffle([Random? random])
Shuffles the elements of this list randomly.
https://api.dart.dev/stable/2.15.1/dart-core/List/shuffle.html
If you want to output your nums
list after it have been shuffled, you just need to print nums
like this after the nums.shuffle()
call:
void main() {
final nums = [1, 2, 3];
nums.shuffle();
print(nums); // [2, 3, 1]
}
If you want to have a new list there is shuffled and based on another list, you can do something like this (the ..
is called a cascade call, you can read more about it here: https://dart.dev/guides/language/language-tour#cascade-notation):
void main() {
final nums = [1, 2, 3];
final shuffeledNums = nums.toList()..shuffle();
print(nums); // [1, 2, 3]
print(shuffeledNums); // [2, 1, 3]
}
Which is the same as this without the use of cascade:
void main() {
final nums = [1, 2, 3];
final shuffeledNums = nums.toList();
shuffeledNums.shuffle();
print(nums); // [1, 2, 3]
print(shuffeledNums); // [2, 1, 3]
}