因此,我尝试使用图像选取器从库中选择图像,并使用REST API将其发送到服务器。从库中选取的图像采用XFILE格式。
BLOC功能将图像发送到服务器:
Future<void> _onPaymentSlipSubmitEvent(
PaymentSlipSubmitEvent event, Emitter<BankTransferScreenState> emit) async {
try {
final ApiResponse apiResponse = await courseRepo.sendBankSlip(BankSlipRequest(courseId: state.courseId,slip:event.slip,paidAmount:state.amount));
if (apiResponse.status) {
}
} on Exception catch (e) {
snackBarBloc.add(OpenSnackBar(e.toString()));
}
}
存储库功能:
Future<ApiResponse> sendBankSlip(BankSlipRequest bankSlipRequest) async {
final ApiResponse apiResponse = await restServiceProvider.post("/courses/create-payment", bankSlipRequest.toJson());
return apiResponse;
}
BankSlipRequest类:
import 'package:care_giver_app/models/api_request.dart';
import 'package:image_picker/image_picker.dart';
class BankSlipRequest extends ApiRequest{
String courseId="";
XFile? slip;
String paidAmount="";
BankSlipRequest({required this.courseId,required this.slip,required this.paidAmount});
BankSlipRequest.fromJson(Map<String, dynamic> json) {
courseId = json['course_Id'];
slip = json['proof_image'];
paidAmount = json['paid_amount'];
}
Map<String, dynamic> toJson() => {
"course_Id": courseId,
"proof_image": slip,
"paid_amount": paidAmount,
};
}
将文件发送到服务器的RestServiceProvider类中的POST方法:
Future<ApiResponse> post(String url, dynamic body) async {
logger.i('Api Post, url $_url$url');
logger.i('Api Post, data ${body.toString()}');
ApiResponse apiResponse;
try {
final response =
await http.post(Uri.parse(_url + url), body: body, headers: _headers);
apiResponse = _returnResponse(response);
} on SocketException {
logger.e('No net');
throw FetchDataException('No Internet connection');
}
return apiResponse;
}
当我试图将文件发送到服务器时,我收到了这个错误
Error: Unhandled error Expected a value of type 'String', but got one of type 'XFile'
occurred in Instance of 'BankTransferScreenBloc'.
我假设这与图像的文件格式(XFile(有关。
在您拾取图像的文件中,您应该访问将返回字符串的8mage的路径。假设您的变量已选定图像
final XFile? selectedImage = await ImagePicker.pickImage(source: ImageSource.gallery);
if(selectedImage!=null){
slip = selectedImage.path;
}