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.08k stars 246 forks source link

How to send @Part fields as null in MultiPart FormData? #567

Open angjelkom opened 1 year ago

angjelkom commented 1 year ago

Is your feature request related to a problem? Please describe. I use Multipart to send formData along with a file with a parameter 'file', now in order to reset the file parameter at backend service I need to send the same parameter but as null so 'file': null.

A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

The problem is even if the parameter is specified as optional:

@PUT('/user/')
  @MultiPart()
  Future<UserData> updateUser({
    @Part() String? name,
    @Part() File? image,
  });

the generated code is:

if (name != null) {
      _data.fields.add(MapEntry(
        'name',
        name,
      ));
    }

if (image != null) {
      _data.files.add(MapEntry(
        'image',
        MultipartFile.fromFileSync(
          image.path,
          filename: image.path.split(Platform.pathSeparator).last,
        ),
      ));
    }

Describe the solution you'd like A clear and concise description of what you want to happen.

I want to be able to send the name and image parameter as null values to backend, I can't send them as empty strings because backend expects a null value and also the code expects optional File type in the case of the image field.

How can we achieve this?

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

Additional context Add any other context or screenshots about the feature request here.

trevorwang commented 1 year ago

It should be get as null if no value provided

dylan-kwon commented 1 year ago

Any news on this issue?

sagarmahobia commented 11 months ago

@ShouldGenerate(
  '''
    final _data = FormData();
    if (image != null) {
      _data.files.add(MapEntry(
        'image',
        MultipartFile.fromFileSync(
          image!.path,
          filename: image.path.split(Platform.pathSeparator).last,
        ),
      ));
    }
''',
  contains: true,
)
@RestApi(baseUrl: 'https://httpbin.org/')
abstract class OptionalFilePartTest {
  @POST('/profile')
  Future<String> setProfile(@Part() File? image);
}

To make it work. The generator will need to satisfy this test case.

trevorwang commented 11 months ago

@sagarmahobia Please use optional parameters here

 Future<String> setProfile({@Part() File? image});
trevorwang commented 11 months ago

@dylan-kwon @angjelkom

Did you mean that the backend only accepted the value with an explicit null value here? For most scenario, the backend should get a null value if the sepecific param dosen't exist.