The `.values` field of a generated enum class contains the zero-valued unspecified value
luangong opened this issue · 2 comments
Given the following .proto
definition:
syntax = "proto3";
enum Color {
COLOR_UNSPECIFIED = 0;
COLOR_RED = 1;
COLOR_GREEN = 2;
COLOR_BLUE = 3;
}
The official documentation says that:
The class will include a
static const Color
for each of the three values defined as well as astatic const List<Color>
containing all the three non-unspecified values.
But the protobuf compiler generates Dart code like this:
class Color extends $pb.ProtobufEnum {
static const Color COLOR_UNSPECIFIED = Color._(0, _omitEnumNames ? '' : 'COLOR_UNSPECIFIED');
static const Color COLOR_RED = Color._(1, _omitEnumNames ? '' : 'COLOR_RED');
static const Color COLOR_GREEN = Color._(2, _omitEnumNames ? '' : 'COLOR_GREEN');
static const Color COLOR_BLUE = Color._(3, _omitEnumNames ? '' : 'COLOR_BLUE');
static const $core.List<Color> values = <Color> [
COLOR_UNSPECIFIED,
COLOR_RED,
COLOR_GREEN,
COLOR_BLUE,
];
static final $core.Map<$core.int, Color> _byValue = $pb.ProtobufEnum.initByValue(values);
static Color? valueOf($core.int value) => _byValue[value];
const Color._($core.int v, $core.String n) : super(v, n);
}
which contains all four values, including COLOR_UNSPECIFIED
.
I’m developing a Flutter app where there are many pull-down buttons and the user can only select one of the menu items, which are derived from the enum values. It would be nice if the .values
list doesn’t contain the XX_UNSPECIFIED
value so that the user must select a meaningful value from the menu. Currently, I have to work around this by excluding the first enum value with .values.sublist(1)
.
The documentation is wrong and we should update it. Even if it describes how it should work in the ideal case, I don't think we can make such a big change now that will potentially break every protobuf enum code in existence.
Closing as it has been fixed in protocolbuffers/protocolbuffers.github.io#149.