How do I handle a List of Lists?
It seems each element of your list is filled with the same instance of []
. If you then do numbers[0].add(0);
numbers[0]
and numbers[1]
show the added 0
because they reference the same list instance.
Changing the list initialization to
List<List<int>> numbers = new List.generate(n, (i) => []);
Shows your expected behavior.
I had the same problem, and was helped by Günter Zöchbauers answer. However, to get proper control over "width" of the "array" I adjusted the code like this:
List <List<num>> graphArray = new List.generate(arrayMaxY, (i) => new List(arrayMaxX));
When arrayMaxY=3 and arrayMaxX=2, the result is:
[[null, null], [null, null], [null, null]]
What was crucial for me was that the methods List.first
and List.last
worked on my "array", and they do with this constructor. Also, this now works as intended:
graphArray[1][0] = 42;print(graphArray); // [[null, null], [42, null], [null, null]]