How to create a matrix in Dart?
List.generate(n, (_) => List.generate(n, (_) => <String>{}));
Magnus
I have delivered value. But at what cost? Bachelor of Science degree in Computer Engineering. ✪ Started out on ATARI ST BASIC in the 1980's, writing mostly "Look door, take key" type games. ✪ Spent a few years in high school writing various small programs for personal use in Delphi. ✪ Learned PHP/SQL/HTML/JS/CSS and played around with that for a few years. ✪ Did mostly Android and Java for a few years. ✪ Graduated from Sweden Mid University with a BSc in Computer Engineering. At this point, I had learned all there was to know about software development, except where to find that darn "any" key... ✪ Currently working with Flutter/Dart and Delphi (again).
Updated on December 12, 2022Comments
-
Magnus over 1 year
I have a
List<String>
and I want to create a square matrix (2-dimensional array/list) ofSet<String>
with the same dimensions as the length of theList<String>
.I tried using
List.filled(entries.length, List.filled(entries.length, Set<String>()));
but the problem is that it seems that each row of my matrix refers to the same list instance, so changing a value in one row changes it in all the others as well.
So then I tried
List.filled(entries.length, List.from(List.filled(entries.length, Set<String>())));
but I still have the same problem. Eventually I surrendered and resorted to
List<List<Set<String>>> matrix = []; for(int i=0; i<entries.length; i++) { List<Set<String>> row = []; for (int n = 0; n<entries.length; n++) { row.add(Set<String>()); } matrix.add(row); }
It works, but it's ugly. Is there a cleaner way to do this?
-
lrn almost 5 yearsWith the new list literal syntax, you can even do:
List<List<Set<String>>> matrix = [for (var _ in entries) [ for (var _ in entries) {} ]];
or... = [for (int i = 0; i < n; i++) [ for (var j = 0; j < n; j++) {}]];
.