Kornel
Kornel

Reputation: 263

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

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.

Upvotes: 3

Views: 1871

Answers (2)

Justine Laserna
Justine Laserna

Reputation: 81

I cannot set a default value this.<List>propertyName = [] in the parameter because the value needs to be const. So I went with not declaring a default value and created a setter/getter.

Here's my example:

[batches.dart]
class Batches{
    String? _batchName;
    List<Trainees>? _trainees;

    // Constructor
    Batches({batchName, trainees}) {
        this.batchName = batchName;
        this.trainees = trainees;
    }

    // Getter Setter
    String? get batchName => this._batchName;
    set batchName(String? batchName) => this._batchName = batchName;

    List<Trainees>? get trainees => this._trainees;
    set trainees(List<Trainees>? traineeList) {
        this._trainees = traineeList;
        print("Added list of trainees to $batchName!");
    }
}

Called the setter function in void main() and then set the existing List batch1_trainees to the setter of the function

[main.dart]
List<Trainees> batch1_trainees = [
    Trainee("Trainee Wan"), 
    Trainee("Trainee Tiu"),
];

Batches batch1 = Batches(batchName: "first_batch");

batch1.trainees = batch1_trainees;

`

Trainees is a class that takes Full_Name as a positional parameter. If the setter is called, the console should print Added list of trainees to first_batch!

PS. The getter and setter were necessary in my example because the properties were set to private.

Upvotes: 0

FDuhen
FDuhen

Reputation: 4816

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

Upvotes: 1

Related Questions