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.05k stars 239 forks source link

toJson will not add if we use freezed. #682

Open b14cknc0d3 opened 3 weeks ago

b14cknc0d3 commented 3 weeks ago

Describe the bug toJson will not add if we use freezed. and show this warning

YourModel must provide a `toJson()` method which return a Map.

To Reproduce Steps to reproduce the behavior:

  1. create a model with freezed

    
    @freezed
    class FoodTagCreateModel with _$FoodTagCreateModel {
    const factory FoodTagCreateModel({
    required String name,
    required String description,
    }) = _FoodTagCreateModel;
    
    factory FoodTagCreateModel.fromJson(Map<String, dynamic> json) =>
      _$FoodTagCreateModelFromJson(json);

}


2. generate a ResApi client that use that model and run build runner

@RestApi() abstract class CrudApi { factory CrudApi(Dio dio, {String? baseUrl}) = _CrudApi;

@POST('/api/v1/my-model') Future createAModel(@Body() MyModel body);

4. See error

MyModel must provide a toJson() method which return a Map. It is programmer's responsibility to make sure the MyModel is properly serialized



**Expected behavior**
If body is not Map force to add toJson() whether it has toJson() or not.
b14cknc0d3 commented 3 weeks ago
@freezed
class FoodTagCreateModel with _$FoodTagCreateModel {
  const factory FoodTagCreateModel({
    required String name,
    required String description,
  }) = _FoodTagCreateModel;

  factory FoodTagCreateModel.fromJson(Map<String, dynamic> json) =>
      _$FoodTagCreateModelFromJson(json);
  @override
  Map<String, dynamic> toJson() => toJson();
}

Temporary solution.

fryette commented 1 week ago

Duplicate. Correct solution is:

  1. Add build.yaml with next snippet
    freezed:
    runs_before:
     - json_serializable 
    json_serializable: 
     runs_before:
      - retrofit_generator