How to declare a List type property for a class correctly in Dart?

Viewed 459

I am new to Flutter, and trying to declare a Folder class with one of the properties being a list of children Folders. I am not able to arrive to a correct declaration, the language gives me various errors. Someone can help me out with that?

class Folder {
  final int id;
  final String title;
  final List<Folder> children;

  Folder ({
    this.id = 0,
    this.title = '',
    this.children
  });

  factory Folder.fromJson(Map<String, dynamic> parsedJson) {
    Iterable i = parsedJson['children'];

    return new Folder(
        id: parsedJson['id'] ?? '',
        title: parsedJson['title'] ?? '',
        children: List<Folder>.from(i.map((model) => Folder.fromJson(model)))
    );
  }
}

This gives me for the children property the following error: The parameter 'children' can't have a value of 'null' because of its type, but the implicit default value is 'null'.

Sometimes the Folder doesn't have subfolders, so I wouldn't like to create a @required parameter, just an optional.

1 Answers

I guess you're using the latest version of Dart with the null-safety enabled ?
If that's the case, declaring your children var this way

List<Folder>? children;

should do the trick.

Another solution would be to update your constructor

  Folder ({
    this.id = 0,
    this.title = '',
    this.children = []
  });
Related