Home > Software design >  Flutter Connection Refused in Localhost
Flutter Connection Refused in Localhost

Time:09-04

enter image description here

SocketException (SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 57014)

CodePudding user response:

I need a few more details in-order to debug this error.

Are you running the server locally or communicating with a remote server? Are you running the app on the Android Emulator? Possible Solution:

If you're running the server locally and using the Android emulator, then your server endpoint should be 10.0.2.2:8000 instead of localhost:8000 as AVD uses 10.0.2.2 as an alias to your host loopback interface (i.e) localhost

Note on Futures

I noticed above that the code is using await and then on the same line. This can be confusing, to be clear, await is used to suspend execution until a future completes, and then is a callback function to execute after a future completed. The same could be written as below

void myFunction() async {
    var data = {};
    var response = await http.post(URL, headers:headers, body:data);
    if (response.statusCode == 200) {
        print(reponse.body);
    } else {
       print('A network error occurred');
    }
}

or the non async/await method

void myFunction() {
    var data = {};
    http.post(URL, headers:headers, body:data)
    .then((response) => print(response.body))
    .catchError((error) => print(error));
}

For a more detailed information on Futures in Dart please read https://www.dartlang.org/tutorials/language/futures

  • Related