Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get response body with request.send() in dart

Tags:

flutter

dart

I'm doing an api request uploading an image with

var request = new http.MultipartRequest("POST", uri); var response = await request.send() 

in dart using flutter. I can then check the response code with for instance

if (response.statusCode == 200) {    print('ok'); } 

with other calls I can also get the response body with

var result = response.body; 

however when using request.send() I can't seem to find out how to get the response body result.

Any help or input is very much appreciated, thanks!

like image 583
Mattias Avatar asked Apr 04 '19 16:04

Mattias


People also ask

What is http Streamedresponse?

An HTTP response where the response body is received asynchronously after the headers have been received.


2 Answers

I checked the docs for request.send I returns Future<StreamedResponse> instead of Future<Response>

Digging more for StreamedResponse I found that it response.stream which is a ByteStream

Here is what you can do to get response in String

final response = await request.send(); final respStr = await response.stream.bytesToString(); 

In my opinoin you should only use request.send if you want streamed response instead of "collected" response. More about streams in dart here

like image 88
Harsh Bhikadia Avatar answered Oct 07 '22 19:10

Harsh Bhikadia


Just use http.Response.fromStream()

import 'package:http/http.dart' as http;  var streamedResponse = await request.send() var response = await http.Response.fromStream(streamedResponse); 
like image 37
Dev Aggarwal Avatar answered Oct 07 '22 19:10

Dev Aggarwal