wahabsohail
wahabsohail

Reputation: 65

In dart how add multiple list in a list?

I want to add multiple List in a List. The Length of the Outer loop is 2 and the length of the inner loop is 2.

List matchName = [];
List a = [];
List b = [];
void getMatchName(GetUserMatchModelRes m) {
  matchName.clear();
  for (var i = 0; i < m.ObjectList.length; i++) {
    matchName.clear();
    matchName.add(
      m.ObjectList[i].ContactName,
    );
    print("i:$i");
    for (var j = 0; j < m.ObjectList[i].ContactPhones.length; j++) {
      print("j:$j");
      matchName.add(
        m.ObjectList[i].ContactPhones[j].MatchedContactName,
      );
    }
   a.add(matchName);
   print(a);
  }
}

Output when outer loop is 0: [[a,b,c]]

When outer loop is 1: [[d,e,f],[d,e,f]]

But I want [[a,b,c],[d,e,f]]

How I can achieve this?

Upvotes: 2

Views: 4464

Answers (1)

jamesdlin
jamesdlin

Reputation: 90155

You're essentially doing:

var outer = <List<String>>[];
var inner = ['foo'];

outer.add(inner);
outer.add(inner);

Now outer has two elements that refer to the same object:

       +---+---+
outer: |   |   |
       +-|-+-|-+
         |   |
         v   v
       +-------+
inner: | 'foo' |
       +-------+     

If you modify inner, you'll see the change in both outer[0] and in outer[1].

To avoid this, you need to add separate objects so that they can be modified independently. Either create new lists to add instead of modifying an existing one:

var outer = <List<String>>[];

outer.add(['foo']);
outer.add(['foo']);

or add copies:

var outer = <List<String>>[];
var inner = ['foo'];

outer.add([...inner]);
outer.add([...inner]);

Upvotes: 4

Related Questions