can someone tell me if there's a way to use enhanced enums in const constructors? I tried both named constructors and factory constructors, with no luck:
enum MyEnum {
first('first-string'),
second('second-string');
final String string;
const MyEnum(this.string);
}
class MyClass {
final String input;
const MyClass({required this.input});
const MyClass.first({
this.input = MyEnum.first.string, //error
});
factory MyClass.second() {
return const MyClass(input: MyEnum.second.string); //error
}
}
Named constructor gives error: The default value of an optional parameter must be constant Factory constructor gives error: A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor. Try using a subtype, or removing the keyword 'const'
Right now the only solution I found was to replace enum with a class containing static const params, like this:
class MyEnumClass {
static const String first = 'first-string';
static const String second = 'second-string';
}
CodePudding user response:
You can use enum
s if you use the enum
type itself for the member.
enum MyEnum {
first('first-string'),
second('second-string');
final String string;
const MyEnum(this.string);
}
class MyClass {
final MyEnum _input;
String get input => _input.string;
const MyClass({required MyEnum input}) : _input = input;
const MyClass.first({
MyEnum input = MyEnum.first,
}) : _input = input;
factory MyClass.second() {
return const MyClass(input: MyEnum.second);
}
}
In general, getters are equivalent to function calls and aren't constant expressions. (There are a some exceptions, and maybe enum
members should be too.)