Skip to content

Commit

Permalink
json_serializable: more enum util cleanup (#1205)
Browse files Browse the repository at this point in the history
Use a field to avoid extra null checks and {} is String interpolation
  • Loading branch information
kevmoo committed Sep 21, 2022
1 parent 12414e0 commit feadf4c
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions json_serializable/lib/src/enum_utils.dart
Expand Up @@ -53,29 +53,30 @@ Object? _generateEntry({
const TypeChecker.fromRuntime(JsonValue).firstAnnotationOfExact(field);

if (annotation == null) {
if (jsonEnum.valueField != null) {
final valueField = jsonEnum.valueField;
if (valueField != null) {
// TODO: fieldRename is pointless here!!! At least log a warning!

final fieldElementType = field.type.element2 as EnumElement;

final e = fieldElementType.getField(jsonEnum.valueField!);
final e = fieldElementType.getField(valueField);

if (e == null || e.isStatic) {
throw InvalidGenerationSourceError(
'`JsonEnum.valueField` was set to "${jsonEnum.valueField}", but '
'`JsonEnum.valueField` was set to "$valueField", but '
'that is not a valid, instance field on '
'`${typeToCode(targetType)}`.',
element: targetType.element2,
);
}

final reader = ConstantReader(field.computeConstantValue());
final valueReader = reader.read(jsonEnum.valueField!);
final valueReader = reader.read(valueField);
if (valueReader.validValueType) {
return valueReader.literalValue;
} else {
throw InvalidGenerationSourceError(
'`JsonEnum.valueField` was set to "${jsonEnum.valueField}", but '
'`JsonEnum.valueField` was set to "$valueField", but '
'that field does not have a type of String, int, or null.',
element: targetType.element2,
);
Expand Down

0 comments on commit feadf4c

Please sign in to comment.