flutterretrofitdio

How to solve exception "toJson() method have to add to MultipartFile" when uploading image?


I'm using the retrofit package with dio in Flutter to upload a file using @MultiPart() and MultipartFile. But when I run build_runner, I get this error:

retrofit_generator on lib/features/schedule/data/datasources/schedule_remote_datasource.dart:
Exception: toJson() method have to add to MultipartFile

Here’s my API method:

@POST(ScheduleConstants.createMeal)
@MultiPart()
Future<void> createMeal({
  @Part(name: 'meal_type') required String mealType,
  @Part(name: 'description') required String description,
  @PartFile(name: 'image') required MultipartFile image,
});

I'm importing MultipartFile from Dio:

import 'package:dio/dio.dart';

I've run

flutter pub get
flutter pub run build_runner build --delete-conflicting-outputs

But the error persists. Is there something I’m missing?


Solution

  • Even though dio internally uses MultipartFile, you don’t need to manually use it in your Retrofit method. Instead, use File type, and it will automatically convert it into MultipartFile.

    @POST(ScheduleConstants.createMeal)
    @MultiPart()
    Future<void> createMeal({
      @Part(name: 'meal_type') required String mealType,
      @Part(name: 'description') required String description,
      @Part(name: 'image') required File image,
    });
    

    After switching to File, the retrofit_generator builds your method and automatically converts the File to MultipartFile in the *.g.dart generated file like this:

      _data.files.add(
        MapEntry(
          'image',
          MultipartFile.fromFileSync(
            image.path,
            filename: image.path.split(Platform.pathSeparator).last,
          ),
        ),
      );
    

    For more information on defining different HTTP methods, refer to the official example of retrofit - https://github.com/trevorwang/retrofit.dart/blob/master/example/lib/example.dart