Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 16 additions & 11 deletions generator/lib/src/generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1871,6 +1871,20 @@ if (T != dynamic &&
return dartType.element3.getMethod2('toJson') != null;
}

/// Gets the expression for serializing an enum value in FormData as a string.
/// Uses toJson() if available, otherwise uses .name.
String _getEnumValueExpression(DartType enumType, String variableName) {
return _hasToJson(enumType) ? '$variableName.toJson()' : '$variableName.name';
}

/// Gets the Reference for serializing an enum value in FormData.
/// Uses toJson() if available, otherwise uses .name.
Expression _getEnumValueReference(DartType enumType, String variableName) {
return _hasToJson(enumType)
? refer(variableName).property('toJson').call([])
: refer(variableName).property('name');
}

/// Generates the query parameters code block.
void _generateQueries(
MethodElement2 m,
Expand Down Expand Up @@ -2455,7 +2469,7 @@ MultipartFile.fromBytes(i,
_isExactly(BuiltList, innerType)))) {
var value = '';
if (innerType != null && _isEnum(innerType)) {
value = 'i';
value = _getEnumValueExpression(innerType, 'i');
} else if (_isBasicType(innerType)) {
value = 'i';
if (innerType != null && !_isExactly(String, innerType)) {
Expand Down Expand Up @@ -2553,16 +2567,7 @@ MultipartFile.fromFileSync(i.path,
if (_isExactly(String, p.type))
refer(p.displayName)
else if (_isEnum(p.type))
_hasToJson(p.type)
? refer(p.displayName)
.property('toJson')
.call([])
.ifNullThen(
refer(
p.displayName,
).property('toString').call([]),
)
: refer(p.displayName).property('toString').call([])
_getEnumValueReference(p.type, p.displayName)
else
refer(p.displayName).property('toString').call([]),
]),
Expand Down
6 changes: 2 additions & 4 deletions generator/test/src/generator_test_src.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1344,12 +1344,10 @@ enum TestEnumWithToJson {
final _data = FormData.fromMap(map);
''', contains: true)
@ShouldGenerate('''
_data.fields.add(MapEntry('enumValue', enumValue.toString()));
_data.fields.add(MapEntry('enumValue', enumValue.name));
''', contains: true)
@ShouldGenerate('''
_data.fields.add(
MapEntry('enumValue', enumValue.toJson() ?? enumValue.toString()),
);
_data.fields.add(MapEntry('enumValue', enumValue.toJson()));
''', contains: true)
@ShouldGenerate('''
final _data = FormData();
Expand Down
Loading