0

I want to get response data from MultipartRequest I uploaded an image to service and I should get image URL in response but I got an Bad state: Stream has already been listened to.

this My code snippet

  //upload image
  Future<ApiResponse> uploadOrderPic(
      {required String orderID,
      required File image,
      required String type}) async {
    ApiResponse apiResponse = ApiResponse();
    var token = await getToken();
    try {
      var request = http.MultipartRequest(
          "POST", Uri.parse(uploadPicUrl));
      request.files
          .add(await http.MultipartFile.fromPath('image', image.path));
      request.fields['id'] = '1084';
      request.fields['type'] = 'invoice';
      request.headers['${HttpHeaders.authorizationHeader}'] = 'Bearer $token';
      request.send().then((value) => http.Response.fromStream(value).then((onValue) {
        try {
          // get response...
          logger.i(value.stream.bytesToString());

        } catch (e) {
          // handle exception
          logger.e(e);// This catch Stream has already been listened to.
        }
      }));
    } catch (e) {
      logger.e(e);
      apiResponse.error = serverError;
    }
    return apiResponse;
  }

the logger.i(value.statusCode); print status code is 200(ok) but logger.i(value.stream.bytesToString()); print exception

FadyFouad
  • 815
  • 6
  • 12
  • use `onValue.body` instead of `value.stream`. As the error suggests, `fromStream` listened to the stream and created a `Response` (which you've called `onValue`) - so use that. – Richard Heap Mar 09 '22 at 14:45
  • Also, It would read better if you replaced all those `then` with `await`. `await request.send()`, `await Response.fromStream(stream);`, – Richard Heap Mar 09 '22 at 14:46

1 Answers1

0

Use the following code block to print the final response body:

final response = await request.send();
log("${(await http.Response.fromStream(response)).body}");
LW001
  • 2,452
  • 6
  • 27
  • 36