For Each

In the following Dart Program, we apply forEach method for a list, a set and a map.

  1. List:

  2. void main() {

      var nums = [1234567];

      nums.forEach((element) {

        element *= 11;

        print(element);

      });

      print(nums);

    }



    11
    22
    33
    44
    55
    66
    77
    [1, 2, 3, 4, 5, 6, 7]


  3. Set:

  4. void main() {

      var eng = {"one""two""three""four""five"};

      var fr = ["un""deux""trois""quatre""cinq"];

      var engAndFr = eng;

      var index = 0;

      engAndFr.forEach((element) {

        element = element + " " + fr[index];

        index++;

        print(element);

      });

      print(engAndFr);

    }



    one un
    two deux
    three trois
    four quatre
    five cinq
    {one, two, three, four, five}


  5. Map

  6. void main() {

      String carDescription = "My car is";

      var car = {

        "model""R8",

        "Horsepower""602",

        "Energy""Gasoline",

        "transmission""automatic"

      };

      car.forEach((key, value) {

        carDescription += " " + value;

      });

      

      print(carDescription);

    }



    My car is R8 602 Gasoline automatic


    You may ask a questio here : Why forEach is unable to modify the elements of the list and the set ?

    The element parameter of the forEach callback is just a normal local variable, and assigning to it has no effect outside the callback.

    Why ?

    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).
    The same goes for iterators: they return the value in the iterable, but it has no reference back to the iterable after that.

         Source