I simply wanted to use forEach
to set all values in a List
to false, but I don't understand why it doesn't work. I created a filled list with fixed length like this:
List<bool> myList = List<bool>.filled(6, false);
Then I set one value to true:
setState(() => myList[3] = true);
Then I try to reset all values to false again, but as you can see from the
setState(() {
myList.forEach((val) => val = false);
print(myList);
});
I/flutter (29049): [false, false, false, true, false, false]
You can check the answer why you can't update the values inside forEach
here: List.forEach unable to modify element?
Dart does not have variable references, all elements are passed as a reference to an object, not to a variable. (In other words, Dart is purely "call-by-sharing" like both Java and JavaScript).
That means that the e parameter to the forEach callback is just a normal local variable, and assigning to it has no effect outside the callback. The same goes for iterators: they return the value in the iterable, but it has no reference back to the iterable after that.
You can do what you want using filled
method like you used to create the list.
setState(() {
myList = List<bool>.filled(myList.length, false);
print(myList);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With