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

1,955

Solution 1

Like this

class Example {
    List<String> myFirstList;
    List<String> mySecondList;

    Example({
        List<String> myFirstList,
        List<String> mySecondList,
    }) : myFirstList = myFirstList ?? [], 
         mySecondList = mySecondList ?? [];
}

Solution 2

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.

Share:
1,955
JakesMD
Author by

JakesMD

Updated on December 28, 2022

Comments

  • JakesMD
    JakesMD over 1 year

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