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?
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With