I've been trying to get this right for some time and can't figure out what is wrong.
enum MyEnum { a, b } class ClassA { final MyEnum myEnum; ClassA({this.myEnum = MyEnum.a}); } class ClassB { final ClassA classA; ClassB({this.classA = ClassA()}); // ClassA expression is underlined with red }
The IDE (Visual Studio Code) complains with:
[dart] Default values of an optional parameter must be constant.
I've tried to prefix it with const
, new
, and passing values to the ClassA
constructor, but nothing works. Can anyone see what I am doing wrong here?
The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.
A parameter wrapped by { } is a named optional parameter. Also, it is necessary for you to use the name of the parameter if you want to pass your argument.
In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value.
Try
enum MyEnum { a, b } class ClassA { final MyEnum myEnum; ClassA({this.myEnum}); } class ClassB { final ClassA classA; ClassB({this.classA}); // ClassA expression is underlined with red }
no need for '=' operator. It will automatically assign the value when you will pass it to the constructor.
Use the '=' operator only when you need to pass a default value to your variables hence, making them optional parameters.
Edit
enum MyEnum { a, b } class ClassA { final MyEnum myEnum; const ClassA({this.myEnum = MyEnum.a}); } class ClassB { final ClassA classA; ClassB({this.classA = const classA()}); // ClassA expression is underlined with red }
This is the only way i could find to achieve what you want, the constructor should be default
This is called a canonicalized constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With