Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why filled Dart list adds to all its elements?

I have a simple code where I create a filled list of integer lists and add an integer to the first element of the list.

  List<List<int>> list = List<List<int>>.filled(2, []);
  list[0].add(1);
  print(list);

What I expect is: [[1],[]]
But in console I get: [[1], [1]]
I can’t understand this behavior, can someone explain why this is happening?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You likely meant to use List.generate. The Dart documentation here references this exact situation. By using filled you are explicitly stating that all of the elements have the same fill value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading