1

I'm trying to create nested Lists but the output I got is not what I have expected.

void main() {
  List<int> row = List();
  List<List<int>> rows = List();

  for(int i=0;i<5;i++)
  {

    row.add(i+1);
    row.add(i+2);
    row.add(i+3);
    rows.add(row);
    row.clear();
  }

  print(rows);
}

The output I got :

[[], [], [], [], []]

The output I was Expecting:

[[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7]]

What changes can I should make run this code properly?

1
  • 1
    On each iteration, you add a reference to the same List instance (row). Since you ultimately clear that instance, you end up with a List of empty Lists. You want to add separate List instances instead (e.g. rows.add([...row]) or rows.add(List<int>.of(row)).) Commented May 20, 2020 at 19:12

3 Answers 3

2

As @shubham answer says, you should create the List inside the for loop because you're referencing the same object, so when you're clearing at the end of the for that also cleanse all the objects inside

Sign up to request clarification or add additional context in comments.

Comments

1

This should help you.

void main() {
  List<List<int>> rows = List();

  for (int i = 0; i < 5; i++) {
    List<int> row = List();
    row.add(i + 1);
    row.add(i + 2);
    row.add(i + 3);
    rows.add(row);
  }
  print(rows); 
}

Comments

0

I think the @Shubham's code is outdated. Try using this:

void main() {
  List<List<int>> rows = [];

  for (int i = 0; i < 5; i++) {
    List<int> row = [];
    row.add(i + 1);
    row.add(i + 2);
    row.add(i + 3);
    rows.add(row);
  }
  print(rows); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.