如何在 built_value EnumClass 中定义字段?
How to define fields in a built_value EnumClass?
我想要一个带有可选 message
字段的 EnumClass
,像这样:
class Status extends EnumClass {
static const Status error = _$error;
static const Status completed = _$completed;
String message;
const Status._(String name) : super(name);
static BuiltSet<Status> get values => _$values;
static Status valueOf(String name) => _$valueOf(name);
}
问题是我收到此错误消息:
Can't define a const constructor for a class with non-final fields.
如果我将 message
声明为 final
,那么我无法初始化它,因为构造函数是隐藏的。
有办法实现吗?也许生成一个枚举生成器?
"enum type" 的目的是创建一组预定义的值。如果您允许客户端创建 Status 的新实例,即使是 const 实例,那 属性 将不再成立;如果传递这样的实例,valueOf()
方法将抛出异常,而 values
将不包含它。所以这违反了 "enum type".
的约定
// BAD: no longer an "enum type" if clients can create new instances
const Status.withMessage(String name, String message)
: message = message, super(name);
另一方面,如果每个枚举值的消息是常量,而不打算由客户端提供,您只需将 getter 添加到 class:
// GOOD: Adding new methods, getters, or const-initialized member variables is fine.
String get message =>
_messages[this] ??
(throw StateError('No message for Status.$name'));
static const _messages = const {
error: "An error occurred.",
completed: "Successfully completed."
};
我想要一个带有可选 message
字段的 EnumClass
,像这样:
class Status extends EnumClass {
static const Status error = _$error;
static const Status completed = _$completed;
String message;
const Status._(String name) : super(name);
static BuiltSet<Status> get values => _$values;
static Status valueOf(String name) => _$valueOf(name);
}
问题是我收到此错误消息:
Can't define a const constructor for a class with non-final fields.
如果我将 message
声明为 final
,那么我无法初始化它,因为构造函数是隐藏的。
有办法实现吗?也许生成一个枚举生成器?
"enum type" 的目的是创建一组预定义的值。如果您允许客户端创建 Status 的新实例,即使是 const 实例,那 属性 将不再成立;如果传递这样的实例,valueOf()
方法将抛出异常,而 values
将不包含它。所以这违反了 "enum type".
// BAD: no longer an "enum type" if clients can create new instances
const Status.withMessage(String name, String message)
: message = message, super(name);
另一方面,如果每个枚举值的消息是常量,而不打算由客户端提供,您只需将 getter 添加到 class:
// GOOD: Adding new methods, getters, or const-initialized member variables is fine.
String get message =>
_messages[this] ??
(throw StateError('No message for Status.$name'));
static const _messages = const {
error: "An error occurred.",
completed: "Successfully completed."
};