Could someone explain what goes wrong in this piece of code?
From the code one (at least myself) would expect that after having ran this code the number list would look like numbers = [[0], [1]]
, but instead it looks like numbers= [[0,1], [0,1]]
.
void main() {
int n = 2;
List<List<int>> numbers = new List.filled(n, []);
for(int i=0; i<n; i++)
for(int j=i+1; j<n; j++ ){
numbers[i].add(0);
numbers[j].add(1);
}
}
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With