Mutlu Simsek
Mutlu Simsek

Reputation: 1172

Dart how to declare growable list of list

I want to initialize a growable list of lists. Both the outer list and all the inner lists should be growable. I tried the following but they they don't work.

List<List<String>> fixturesOfLeagues = List<List<String>>();
List<List<String>> fixturesOfLeagues = [];
List<List<String>> fixturesOfLeagues = [[]];

Any idea how to do it?

Upvotes: 1

Views: 9535

Answers (1)

Naslausky
Naslausky

Reputation: 3768

As stated in the comments, you need to create each list separately and add them to them list of lists.

They are growable by default, according to the docs:

The default growable list, as returned by new List() or [], keeps an internal buffer, and grows that buffer when necessary.

Example use of the code above:

void main() {

  List<List<String>> fixturesOfLeagues = List<List<String>>();

  for (int i=0; i < 5 ; i++){
    List<String> ListToBeAdded = ['$i'];
    fixturesOfLeagues.add(ListToBeAdded); //create a list and adds to the outter list.
  }

  print(fixturesOfLeagues);

  fixturesOfLeagues[2].add('test');

  print(fixturesOfLeagues);
}

Which outputs:

[[0], [1], [2], [3], [4]]
[[0], [1], [2, test], [3], [4]]

Upvotes: 1

Related Questions