trevorwang / retrofit.dart

retrofit.dart is an dio client generator using source_gen and inspired by Chopper and Retrofit.
https://mings.in/retrofit.dart/
MIT License
1.07k stars 246 forks source link

Empty response Body cast exception #526

Open Gradergage opened 1 year ago

Gradergage commented 1 year ago

Some queries can return Nullable elements For example

  @GET('/get/osettings')
  Future<OperationSettings?> getOperationSettings(@Query('settingsId') int id);

Generated implementation

  @override
  Future<OperationSettings?> getOperationSettings(id) async {
    const _extra = <String, dynamic>{};
    final queryParameters = <String, dynamic>{r'settingsId': id};
    final _headers = <String, dynamic>{};
    final _data = <String, dynamic>{};
    final _result = await _dio.fetch<Map<String, dynamic>?>(
        _setStreamType<OperationSettings>(
            Options(method: 'GET', headers: _headers, extra: _extra)
                .compose(_dio.options, '/get/osettings',
                    queryParameters: queryParameters, data: _data)
                .copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl)));
    final value =
        _result.data == null ? null : OperationSettings.fromJson(_result.data!);
    return value;
  }

Spring backend endpoint

    @GetMapping("/get/osettings")
    fun getDeviceOperationSettings(@RequestParam settingsId: Int): ResponseEntity<OperationSettings?> {

        val settings: OperationSettings? = operationSettingsRepository.getOneById(settingsId)

        return ResponseEntity<OperationSettings?>(
            settings,
            HttpStatus.OK
        )
    }

When backend returns null in body it becomes empty string "" and i get this error

Error: DioError [DioErrorType.other]: Expected a value of type 'Map<String, dynamic>?', but got one of type 'String'

How to prevent this in cases with empty null body?

OmarYehiaDev commented 1 year ago

@Gradergage Did you find any solution?