Search code examples
listflutterdartparametersdefault

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


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?
}

Solution

  • 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.