6

While retrieving the image file from network http://10.0.2.2:8000 localhost I got the following error:
Connection closed while receiving data.

I have an error when I call data (images only) from the URL.
Note that I am using a local server.
I’m trying to put the image inside Image.network(), this is image code.

Image.network(urllink)

The same URL works properly in the localhost browser and postman also.
I am trying to retrieve images in the decoration box widget.
The same url and image work when I paste direct url in the network image function but an error occurred when I tried to fetch the photoname through the apis. The photoname and APIs I am getting are working fine. There is not any problem with it.

 child: FutureBuilder<MatrimonyProfileData>(
                  future: futureMData,
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      // String matrimonyUrl = '/$matrimonyprofileUrl';
                      String photoName = snapshot.data!.matrimonies.photo;

                      print(photoName);
                      //var fullUrl = _url + apiUrl

                      var url;
                      // urllink = 'http://10.0.2.2:8000/matrimony/profile.jpg';

                      **url = (webLink + matrimony + photoName);
                      print(url);
                      String urllink = Url;**
                      return Column(
                        children: [
                          Container(
                            color: Colors.deepPurpleAccent.shade100,
                            child: Column(
                              children: <Widget>[
                                Container(
                                  margin: const EdgeInsets.all(15.0),
                                  padding: const EdgeInsets.all(3.0),
                                  decoration: BoxDecoration(
                                      border: Border.all(
                                          color: Colors.black, width: 3)),
                                  child: Wrap(
                                    // mainAxisAlignment: MainAxisAlignment.end,
                                    // direction: Axis.vertical,
                                    children: <Widget>[
                                      
                                Container(
                                  height: 300,
                                  width: 400,
                                  //color: Colors.amber,
                                  child: Row(
                                    children: <Widget>[
                                      Container(
                                          height: 300,
                                          width: 170,
                                          //color: Colors.amber,
                                          decoration: BoxDecoration(
                                            image: DecorationImage(
                                                image: **NetworkImage(urllink),**

                                                
                                                fit: BoxFit.fitWidth),
                                            
                                          )),
                                      // SizedBox(
                                      //   width: 20,
                                      // ),

same problem on this link also https://askandroidquestions.com/2021/07/12/flutter-exception-connection-closed-while-receiving-data/

nicks101
  • 1,065
  • 11
  • 20
Purvekta
  • 59
  • 1
  • 2
  • Share your http request code from which you are retrieving this network url? – Muhammad Hussain Jan 18 '22 at 11:33
  • class Network { final String _url = siteUrl; var token; _getToken() async { return token; } getData(apiUrl) async { return await http.get(Uri.parse(fullUrl), headers: _setHeaders()); } _setHeaders() => { 'Content-type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer $token', "Connection": "Keep-Alive", }; – Purvekta Jan 28 '22 at 15:44

2 Answers2

2

You might be missing Keep-Alive header in your http request.

Try adding this to your request headers:

  "Connection": "Keep-Alive",
Muhammad Hussain
  • 966
  • 4
  • 15
0

This is a bit of a hack, but it seems to have worked for me.

I have a server running flask and my flutter app calls back to that for data. I also got the same error, but not with NetworkImage specifically, but this should also work for that too.

I also went searching for answers and have added not only the 'Connection' : 'keep-alive' and "Keep-Alive": "timeout=20, max=5" headers, but to no success. So this is what I've done to not solve the issue completely, but it does significantly lower the chances of getting that error.

Basically I have generic api call functions to handle sending data and image data to the server, and I've wrapped the parts of those functions that actually make the http requests in a while loop that uses tracking variables to check if a response was received or not during the allotted number of attempts.

This is basically the idea to follow:

// make sure to get your data ready above here, if any
int attempts = 5;
bool gotResponse = false;
String errMsg = "";

while (attempts > 0) {
    attempts = attempts - 1;
    try {
        // this is where you make the http.get or http.post request
        // once you have a response and validate it, then set
        // gotResponse = true
    } catch (err) {
        // set your tracking variables for failure checking here
        gotResponse = false;
        errMsg = err.toString();
    }
}

if (gotResponse == false) {
    throw Exception("$errMsg");
} else {
    throw Exception("Everything's broken");
}

It might not be a very elegant solution, but it got the job done for me. And at least you can specify how many times to retry the connection if you have a similar issue to me where the connection sometimes closes multiple times in a row.

Hope this helps.

KyleDev
  • 11
  • 1
  • 5