簡體   English   中英

[Flutter 錯誤] - 期望“String”類型的值,但在嘗試將圖像發送到服務器時得到“XFile”類型之一錯誤

[英][Flutter Error ]-Expected a value of type 'String', but got one of type 'XFile' Error whe trying to send an image to the server

因此,我嘗試使用圖像選擇器和 select 從圖庫中獲取圖像,並使用 REST API 將其發送到服務器。從圖庫中選擇的圖像是 XFILE 格式。

BLOC function 將圖像發送到服務器:

  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()));
     }
    }

存儲庫 function:

    Future<ApiResponse> sendBankSlip(BankSlipRequest bankSlipRequest) async {
    final ApiResponse apiResponse = await restServiceProvider.post("/courses/create-payment", bankSlipRequest.toJson());
    return apiResponse;
    }

BankSlipRequest class:

    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 class 中的 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 的路徑。 說你的變量是 selectedImage

final XFile? selectedImage = await ImagePicker.pickImage(source: ImageSource.gallery);
if(selectedImage!=null){
   slip = selectedImage.path;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM