Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Not understanding how forEach is supposed to work

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 print output it does not work:

setState(() {
  myList.forEach((val) => val = false);
  print(myList);
});

I/flutter (29049): [false, false, false, true, false, false]

like image 670
Hasen Avatar asked Mar 03 '23 04:03

Hasen


1 Answers

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);
});

like image 167
diegoveloper Avatar answered Mar 12 '23 00:03

diegoveloper