How to create a matrix in Dart?

1,480
List.generate(n, (_) => List.generate(n, (_) => <String>{}));
Share:
1,480
Magnus
Author by

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, 2022

Comments

  • Magnus
    Magnus over 1 year

    I have a List<String> and I want to create a square matrix (2-dimensional array/list) of Set<String> with the same dimensions as the length of the List<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
    lrn almost 5 years
    With 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++) {}]];.