Ive 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({th
For ClassA
to be able to create constant values, the constructor must be marked as const.
enum MyEnum { a, b }
class ClassA {
final MyEnum myEnum;
const ClassA({this.myEnum = MyEnum.a}); // <- constructor is const.
}
class ClassB {
final ClassA classA;
ClassB({this.classA = const ClassA()}); // <- creation is const
}
You need to write const
for the object creation, even if only constant values are allowed as default values. The language do not automatically insert a const
in that position because the language team wants to reserve the option of allowing non-constant default values at some point.
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.