I am programming in Dart and I need a multi-dimensional array to be filled with some data. But when I tried to run it, data at previous indexes were overwritten.
Here is my code:
List<List<String>> list = List.filled(4, List.filled(4, ""));
String toFill = "abcdefghijklmnop";
for (int i = 0; i < 4; i ) {
for (int j = 0; j < 4; j ) {
list[i][j] = toFill[i * 4 j];
}
}
print(list);
I expected output of print()
function to be
[[a, b, c, d], [e, f, g, h], [i, j, k, l], [m, n, o, p]]
but when I run it, it printed
[[m, n, o, p], [m, n, o, p], [m, n, o, p], [m, n, o, p]]
I don't know, why the last part is duplicating over to previous values.
I'd be glad for any help.
Thanks
CodePudding user response:
I was able to solve this use List.generate which makes a new list from an iterable.
List<List<String>> list = List.generate(4, (int index) => List.generate(4, (int index) => ""));
Which gives me
> [[a, b, c, d], [e, f, g, h], [i, j, k, l], [m, n, o, p]]
This seems a little verbose, so there may be a shortcut to do the same thing.
Edit: Since you don't care about the index
variable, you can shorten it somewhat but ignoring it:
List<List<String>> list = List.generate(4, (_) => List.generate(4, (_) => ""));
CodePudding user response:
You could also combine the creating and filling the list:
import 'dart:math';
void main() {
String toFill = "abcdefghijklmnopqrstuvwxyz";
List<List<String>> list = List.generate(
(toFill.length/4).ceil(),
(i) => toFill.substring(i*4, min(toFill.length, (i 1)*4)).split(''),
);
print(list);
}
[[a, b, c, d], [e, f, g, h], [i, j, k, l], [m, n, o, p], [q, r, s, t], [u, v, w, x], [y, z]]
Which, if your string is always 16 characters long, can be simplified to:
void main() {
String toFill = "abcdefghijklmnop";
List<List<String>> list = List.generate(
4,
(i) => toFill.substring(i*4, (i 1)*4).split(''),
);
print(list);
}