Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The .values field of a generated enum class contains the zero-valued unspecified value #919

Closed
luangong opened this issue Mar 4, 2024 · 2 comments

Comments

@luangong
Copy link

luangong commented Mar 4, 2024

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 a static 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).

image

@osa1
Copy link
Member

osa1 commented Mar 7, 2024

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.

@luangong
Copy link
Author

Closing as it has been fixed in protocolbuffers/protocolbuffers.github.io#149.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants