Dart: how to create an empty list as a default parameter
Asked Answered
J

2

23

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?
}
Jackelinejackelyn answered 6/3, 2021 at 11:0 Comment(0)
P
22

Like this

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.

Paralyze answered 6/3, 2021 at 11:7 Comment(1)
Thanks! Can't believe I didn't think of that myself ;)Jackelinejackelyn
C
9

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.

Cousins answered 14/10, 2021 at 1:14 Comment(1)
Thanks. Also, if your class is immutable (const constructor and final fields) then you need to use const [] in the initializer expressions.Misquote

© 2022 - 2024 — McMap. All rights reserved.