Search code examples
flutterhttpsflutter-futurebuilder

How to return response from HttpClientResponse in flutter


I am using HttpClient in flutter to get data from my API, here is my function

I am trying to return the value from the response function.

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

The function SendOTPtoVerify works fine and the API send me the response but I can only print it, what I wanted is to returned it, in order to use it in other classes. This is my code in other class but it return nothing even I am usin the FutureBuilder widget

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

Note that I am obliged to use HttpClient and the event is printed correcty but I could not return its value


Solution

  • Try this way:

      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;
    

    Here, result is your desired response from API.

    Feel free to let me know if you've any questions.

    Happy coding.