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, []);

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?

>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.

Leave a Reply