【问题标题】:How to return response from HttpClientResponse in flutter如何在颤动中从 HttpClientResponse 返回响应
【发布时间】:2021-04-16 18:07:16
【问题描述】:

我在 Flutter 中使用 HttpClient 从我的 API 获取数据,这是我的函数

我正在尝试从响应函数返回值。

    Future<String> SendOTPtoVerify(
    {String endpoint, String number, String OTP}) async {
  try {
    var client = new HttpClient();
    client.badCertificateCallback =
        ((X509Certificate cert, String host, int port) => true);
    Map valueMap;
    await client.postUrl(Uri.parse(endpoint)).then((HttpClientRequest request) {
      String body = '{"mobileNumber": "$number","code": "$OTP"}';
      request.contentLength = body.length;
      request.headers.contentType =
          new ContentType("application", "json", charset: "utf-8");
      request.write(body);
      return request.close();
    }).then((HttpClientResponse response) {
      response.transform(utf8.decoder).listen((event) {
        valueMap = json.decode(event);
     // this print works fine and prints the desired result 
        print("this is the event $event");
      });
      // I added this return in order to get the event as variable
      return event;
    });
   
  } catch (e) {
    print('Error: $e');
  }
}

函数SendOTPtoVerify 工作正常,API 向我发送响应,但我只能打印它,我想要返回它,以便在其他类中使用它。 这是我在其他课程中的代码,但即使我在 FutureBuilder 小部件中使用它也不会返回任何内容

                 PinFieldAutoFill(
                        codeLength: 6,
                        onCodeChanged: (val){
                        if(val.length == 6 ) {
                          FutureBuilder(
                              future: SendOTPtoVerify(number: widget.full_number,
                                  endpoint: "https://my_api.servehttp.com:3000/api/codeValidation",
                                  OTP: val),
                              builder: ( BuildContext context , AsyncSnapshot snapshot){
                               // this print show nothing when I run the app 
                                print("this is the builder");
                               // even this container is not returned
                                return Container(child: Text(snapshot.data),);
                                  },
                               );
                             }
                           },
                         ),

请注意,我必须使用 HttpClient 并且事件打印正确,但我无法返回其值

【问题讨论】:

    标签: flutter https flutter-futurebuilder


    【解决方案1】:

    试试这个方法:

      var headers = {
        "Authorization": user.token,
        "Content-Type": "multipart/form-data; boundary=<calculated when request is sent>",
      };
    
      var request = MultipartRequest('POST', Api.saveData);
    
      request.fields.addAll({
        "Model": model.trim(),
        "Brand": brand.trim(),
        "MAC": version.trim(),
        "IMEI": appVersion.trim(),
        "PhoneNumber": (user.phone ?? "").trim(),
      });
    
      for (var file in files) {
        request.files.add(
          await MultipartFile.fromPath("ListFiles", file.path),
        );
      }
    
      request.headers.addAll(Map<String, String>.from(headers));
    
      var response = await request.send();
      String result = await response.stream.bytesToString();
      return response.statusCode;
    

    这里,result 是您希望来自API 的回复。

    如果您有任何问题,请随时告诉我。

    编码愉快。

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 2019-07-30
      • 2020-07-07
      • 1970-01-01
      相关资源
      最近更新 更多