Flutter Web中Retrofit用MultipartFile构建报错:需添加toJson()方法
解决Retrofit Multipart上传时“toJson() method have to add to MultipartFile”构建异常
问题场景
Flutter Web应用中,因file_picker无法获取文件路径,改用MultipartFile配合Retrofit的@MultiPart实现文件上传,执行build_runner构建时抛出以下异常:
Exception: toJson() method have to add to MultipartFile
相关API代码:
@POST("upload") @MultiPart() Future<UploadFileResponse> uploadWallpaperImage( @Part(name: "files") MultipartFile wallpaperImage, @Query("populate") String populate );
解决方法
方法1:升级Retrofit相关依赖版本
异常大概率是retrofit与retrofit_generator版本不兼容导致的,将依赖升级到最新稳定版:
在pubspec.yaml中更新版本:
dependencies: retrofit: ^4.0.1 # 替换为最新稳定版 dio: ^5.4.0+1 # 确保与retrofit版本匹配 dev_dependencies: retrofit_generator: ^8.0.0 # 替换为最新稳定版 build_runner: ^2.4.6
执行依赖更新:
flutter pub get
方法2:使用@PartFile注解替代@Part
将@Part替换为@PartFile,适配Web环境下的MultipartFile传入:
修改API定义:
@POST("upload") @MultiPart() Future<UploadFileResponse> uploadWallpaperImage( @PartFile(name: "files") MultipartFile wallpaperImage, @Query("populate") String populate );
方法3:扩展MultipartFile添加toJson方法
若不想升级依赖,可通过扩展方法给MultipartFile补充toJson实现:
创建扩展文件(如multipart_file_extension.dart):
import 'package:dio/dio.dart'; extension MultipartFileJson on MultipartFile { Map<String, dynamic> toJson() { return { 'filename': filename, 'length': length, 'contentType': contentType?.toString(), }; } }
在API文件中导入该扩展:
import '../path/to/multipart_file_extension.dart'; @POST("upload") @MultiPart() Future<UploadFileResponse> uploadWallpaperImage( @Part(name: "files") MultipartFile wallpaperImage, @Query("populate") String populate );
验证构建
执行构建命令(使用官方推荐的dart run替代旧命令):
dart run build_runner build --delete-conflicting-outputs
内容的提问来源于stack exchange,提问作者63 - Vikas Kumar 4rd Sem.
相关产品推荐
相关产品推荐

