Home > OS >  Flutter/Dart global List variable changed in a foreach loop is unchanged after the loop
Flutter/Dart global List variable changed in a foreach loop is unchanged after the loop

Time:09-08

I have a list declared outside a for loop and then I assign some values to this list inside that for loop and its value is updated when printed inside the loop but when I print it after the loop, it gives me an empty list.

  List<List<String>> chunkSizeCollection(List<String> followedList) {
    int counter = 0;
    int ongoingCounter = 0;
    bool isLessThanTen = false;
    List<List<String>> returnAbleChunkedList = [];
    List<String> midList = [];
    log("in followedlist");
    followedList.forEach((element) {
      if (counter == 0) {
        int difference = followedList.length - ongoingCounter;
        if (difference < 10) {
          // log("in difference if: $difference");
          isLessThanTen = true;
        }
      }
      midList.add(element);
      counter  ;
      ongoingCounter  ;
      if (counter == 10 || (isLessThanTen && ongoingCounter == followedList.length)) {
        returnAbleChunkedList.add(midList);
        log("returnAbleChunkedList in counter 10 after adding new val is: $returnAbleChunkedList");
        //above log works properly and prints the updated list
        midList.clear();
        counter = 0;
      }
    });
    //this log on the other hand, returns an empty list
    log("returnAbleChunkedList: $returnAbleChunkedList before return");
    return returnAbleChunkedList;
  }

The output:

[log] returnAbleChunkedList in counter 10 after adding new val is: [[KQTuEPllbmRrlBNvYgZ7oUXwtA63, OZUZOE10IzT8quUFoZbNxZOynU32, fCYIlYemCvbLTc7SpNHw6fCHrcm1, CbcLrtDNOdYZyC23FzEehOrJbKx2, FFvvVHCpPGNKUiXPQD34QdoPqH32, Gk09y59vSVXa1HNhzYvc6Atqnt53, JDO356z8urYQvuktJmc6eNUYqSm2, YesvvNI43gUVYPMfqhG4uRO5t6K2]]

[log] returnAbleChunkedList: [[]] before return

CodePudding user response:

In this line:

      returnAbleChunkedList.add(midList);

you add a reference to midList to your output list. If your input is longer than 10, you'll end up adding more than one reference to midList to the output list (i.e. you might now have 2). Subsequently, you clear midList so you now have an output list that contains 2 references to a list that you've now cleared, so you end up with a list containing 2 empty lists.

If, instead, you changed this to:

      returnAbleChunkedList.add(midList.toList());

you'd add a copy of midList to your output list and your end up with:

[[a, b, c, d, e, f, g, h, i, j], [k]]

as you expected.

CodePudding user response:

The problem is this:

returnAbleChunkedList.add(midList);
midList.clear();

You add the object midlist to the list and then you clear it. So the object you added will be emptied. You have to create a copy or add the elements of the list.

returnAbleChunkedList.add(midList.toList());
// or
returnAbleChunkedList.add(List.of(midList));
// or
returnAbleChunkedList.add([...midList]);
  • Related