Struggling to add data to a specific index of a 2D array. I’m quite new to programming so I could have this all completely wrong but any help would be appreciated.
Maybe my declaration of the array is wrong but I am seeing the first pair of [] as the first part where data can be stored, and then the second set inside the first [] is another place where I can store data and this data is linked to the data in the first pair of []
I’m very sorry if I’m not explaining this properly.
void main(){
var staff = [[]];
int a = 1;
int b = 2;
staff[0][0].add(b)
staff[0][1].add(a)
staff[1][0].add(b)
staff[1][1].add(a)
print(staff);
}
Ideally I would like an output that looks something like this
[2,1][2,1]
Cheers 😀
>Solution :
Dart is not JavaScript. Arrays (List
s) are not automatically grown when accessing out-of-bounds elements. You must explicitly grow your List
s to have the desired lengths:
void main() {
var staff = [
for (var i = 0; i < 2; i += 1)
[
for (var j = 0; j < 2; j += 1) 0,
],
];
int a = 1;
int b = 2;
staff[0][0] = b;
staff[0][1] = a;
staff[1][0] = b;
staff[1][1] = a;
print(staff); // Prints: [[2, 1], [2, 1]]
}
Alternatively, if you want to grow your List
s dynamically:
void main() {
var staff = <List<int>>[];
int a = 1;
int b = 2;
staff.add([b, a]);
staff.add([b, a]);
print(staff); // Prints: [[2, 1], [2, 1]]
}