App/Flutter

[Flutter] Retrofit_generator exception - toJson() method have to add to List<xxx>

Agrafenaaa 2023. 10. 10. 10:24
[SEVERE] retrofit_generator on lib/services/client_api.dart:
Exception: toJson() method have to add to List<ImageList>

@MultiPart()
@PUT('$xxx/xxx')
Future<String> modifyFoodDiaryImages(
  @Part(name: 'list') List<ImageList> list,
  @Part(name: 'files') List<File> files,
);

Issue : The 'Part' of http, which is a List<File>, throws an exception when generating a client api g.dart file. It worked perfectly before upgrading to the specs below.  

flutter => 3.13.6
dart => 3.1.3
dio: ^5.3.2
retrofit: ^4.0.2
json_annotation: ^4.8.1
freezed_annotation: ^2.4.1

retrofit_generator: ^8.0.0
json_serializable: ^6.6.2
build_runner: ^2.4.6

The related dependencies' versions were in accordnace with the guide of 'retrofit'. 

 

Solution

 

The problem was that 'retrofit_generator' runs BEFORE 'json_serializable', which is used for the model class 'ImageList'.

1. Create a 'build.yaml' file in the same directory as 'pubspec.yaml'. 

2. Set global options in the file. 

# build.yaml
global_options:
  freezed:
    runs_before:
      - json_serializable
  json_serializable:
    runs_before:
      - retrofit_generator

3. Re-run "build_runner".

dart run build_runner watch --delete-conflicting-outputs

 

Reference : https://github.com/trevorwang/retrofit.dart/issues/609