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

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


Like this

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


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.


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