Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values of an optional parameter must be constant

Tags:

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?

like image 827
mg74 Avatar asked Aug 18 '18 09:08

mg74


People also ask

What are the parameter that are default values?

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.

Can parameters be optional?

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.

How do you pass optional parameters in darts?

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.

Are parameters always optional in JavaScript?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value.


1 Answers

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.

like image 192
Jaswant Singh Avatar answered Sep 18 '22 03:09

Jaswant Singh