Reputation: 2166
I have multiple lists that need to be empty by default if nothing is assigned to them. But I get this error:
class Example {
List<String> myFirstList;
List<String> mySecondList;
Example({
this.myFirstList = []; // <-- Error: default value must be constant
this.mySecondList = [];
});
}
But then of course if I make it constant, I can't change it later:
Example({
this.myFirstList = const [];
this.mySecondList = const [];
});
...
Example().myFirstList.add("foo"); // <-- Error: Unsupported operation: add (because it's constant)
I found a way of doing it like this, but how can I do the same with multiple lists:
class Example {
List<String> myFirstList;
List<String> mySecondList;
Example({
List<String> myFirstList;
List<String> mySecondList;
}) : myFirstList = myFirstList ?? []; // <-- How can I do this with multiple lists?
}
Upvotes: 25
Views: 12279
Reputation: 2529
class Example {
List<String> myFirstList;
List<String> mySecondList;
Example({
List<String>? myFirstList,
List<String>? mySecondList,
}) : myFirstList = myFirstList ?? [],
mySecondList = mySecondList ?? [];
}
If your class is immutable (const constructor and final fields) then you need to use const [] in the initializer expressions.
Upvotes: 24
Reputation: 153
Expanding on YoBo's answer (since I can't comment on it)
Note that with null-safety enabled, you will have to add ?
to the fields in the constructor, even if the class member is marked as non-null;
class Example {
List<String> myFirstList;
List<String> mySecondList;
Example({
List<String>? myFirstList,
List<String>? mySecondList,
}) : myFirstList = myFirstList ?? [],
mySecondList = mySecondList ?? [];
}
See in the constructor you mark the optional parameters as nullable (as not being specefied in the initialization defaults to null), then the null aware operator ??
in the intitializer section can do it's thing and create an empty list if needed.
Upvotes: 10