google / google/built_value.dart
EnumClass: Support using wireName as the discriminated value.
- Dominant language
- Dart
- Stars
- 886
- Forks
- 195
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 4
Description
For example, here is the current behavior:
```dart
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
part 'main.g.dart';
class Drink extends EnumClass {
@BuiltValueEnumConst(wireName: 'gin-and-tonic')
static const Drink ginAndTonic = _$ginAndTonic;
@BuiltValueEnumConst(wireName: 'old-fashioned')
static const Drink oldFashioned = _$oldFashioned;
const Drink._(String name) : super(name);
static Serializer get serializer => _$drinkSerializer;
static BuiltSet get values => _$values;
static Drink valueOf(String name) => _$valueOf(name);
}
void main() {
print(Drink.oldFashioned.name); // oldFashioned
}
```
It would be nice, as an option, to use `wireName: ...` as the identity value:
```dart
@BuiltValueEnum(useWireNameAsValue: true)
class Drink extends EnumClass {
// ...
}
void main() {
print(Drink.oldFashioned.name); // old-fashioned
}
```
My rationale for this is for the web (and mobile, with deep linking), using hyphenated values is much more common (and easier to read and write). For example, If I wanted to see a recipe, I might visit `localhost/drinks/old-fashioned`, and it would be nice to do `Drinks.valueOf('old-fashioned')`.
I have found a (hacky) workaround, which is:
```dart
class Drink extends EnumClass {
// ...
/// Use instead of [valueOf].
factory Drink.from(String name) {
final identity = _$DrinkSerializer._fromWire[name];
return valueOf(identity);
}
@override
String get name => _$DrinkSerializer._toWire[super.name];
// ...
}
```
It works for my needs, but it's not perfect. Another option is allowing users to custom implement `valueOf` (i.e. I could move `Drink.from` to `Drink.valueOf`).
Contributor guide
Assessment
This issue has not been assessed yet.