bluefroq
bluefroq

Reputation: 61

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

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

Upvotes: 6

Views: 19389

Answers (2)

CoderSteve
CoderSteve

Reputation: 1

Make the comments a @required parameter. This would make your code look like this...

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

    @required this.comments,
  });

  final String data1;
  final String data2;

// List of comments for one ArrayItem

  List<TextData> comments;
}

At least this way you will be prompted to add an empty list when you instantiate a new Data object like so...

var data = Data(comments: []);

This is what I've done in my Flutter Classes where I want to make sure that there is an empty list so that I don't have to check it before adding anything to that list.

Upvotes: 0

Gaspard Merten
Gaspard Merten

Reputation: 1233

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

List<TextData> comments = []

instead of

List<TextData> comments;

Upvotes: 10

Related Questions