Flutter: How to initialize an empty list for every Object in an Array?

bluefroq picture bluefroq · Jul 12, 2019 · Viewed 7.1k times · Source

Hi I'm very new to flutter and coding in general therefore my approach on this might not be the cleanest. Anyways:

I'm storing data in an Array and use the Array-Items to build ListTiles. Now I want to add the possibility to write comments to a Tile and store the input-data like author-name, time and the Comment-Text to the Array/Item. As there aren't any comments in the beginning, every Item should have an empty List of comments to start with. When I initialize the empty list for a single Item it works and I can add TextData to the list. But because my Array is very large I can't initialize the empty list for every single Item. Therefore I'm searching for a way to set the default for every Item to be an empty list without the List being a const List, as I can't add to the const List.

// DataType to store a single comment with further information

class TextData {
  Text({
    this.text,
    this.author,
    this.time,
});
  final String text;
  final String author;
  final time;
}

//All the Data for one ArrayItem including a List of Comments

class Data {
  Data({
    this.data1,
    this.data2,

    this.comments,
  });

  final String data1;
  final String data2;

// List of comments for one ArrayItem

  List<TextData> comments;
}

I don't get any error messages I just can't add to the list if it isn't initialized or its initialized as a default.

I appreciate any Help. Thanks in advance

Answer

Gaspard Merten picture Gaspard Merten · Jul 12, 2019

Why don't you just write that in your Data class:

List<TextData> comments = []

instead of

List<TextData> comments;