Sdk: List as optional constructor parameter is null

Created on 19 Apr 2020  路  6Comments  路  Source: dart-lang/sdk

I would like to pass an optional named (growable) list as a constructor parameter.

I declare an empty list in the class.

When i do create a class, but dont pass a parameter for the list, it is set to null. I expected an empty list in the assertion.

Example:

class MyListClass {
  List myList = [];

  MyListClass({this.myList});
}

void main() {
  final obj = MyListClass();
  assert(obj.myList != null);
}

See my stack overflow question here:
https://stackoverflow.com/questions/61303649/initialise-class-parameter-with-default-value

Not sure if it is related to:
https://github.com/dart-lang/sdk/issues/21406

dart --version

Dart VM version: 2.7.2 (Mon Mar 23 22:11:27 2020 +0100) on "macos_x64"

im on macOS 10.15.4

area-language closed-as-intended type-question

All 6 comments

This is working as intended. Default value for your named parameter is null, so you initialize the field with null if you don't pass anything.

@mraleph i would expect the the value to be null only if i set MyListClass(myList: null)

What is the best way to optionally assign a list, but default to an empty ( growable ) list?

When you write f({this.x}) that means f({this.x : null}).

Default initializers can only be constants, so your best bet is f({List x}) : x = x ?? [];

@mraleph Is there any change in dart language? Because this was working few releases ago... I have removed constructor and it works as intended class MyListClass { List myList = [];} Another thing .. what is the point of the constructor now? Do we need to create a constructor? I have removed all my constructors in my classes which were needed in previous versions and now I've got no issue without them

Is there any change in dart language?

No, this was always supposed to work like that.

Because this was working few releases ago...

I am fairly certain it did not actually work and you are misremembering.

I have removed constructor and it works as intended class MyListClass { List myList = [];}

Except that now you can't do MyListClass(myList: something).

Another thing .. what is the point of the constructor now? Do we need to create a constructor?

The point of constructor is to contain initialization code which can't be expressed just in terms of field initializers and to call appropriate super constructor.

If you don't create a constructor you get default constructor - which is empty and is calling default super constructor.

I have removed all my constructors in my classes which were needed in previous versions and now I've got no issue without them

Well if you never called your constructors with parameters and you only need field initializers - then you certainly don't need any constructors.

Except that now you can't do MyListClass(myList: something).

Right... sorry that is correct

Was this page helpful?
0 / 5 - 0 ratings