Not able to fetch data in flutter from local web server

Viewed 435

I'm trying to fetch data from a web server running on http://localhost:5050 and print it. At first it gave me a Socket Exception, so I looked it up and looks like you're supposed to replace "localhost" with your computer's IP address, so I did that, and now when I fetch it, it just seems to be... stuck? I have a print statement after the request but it doesn't print anything, no error, no output.. nothing. I'm using a Physical device, Here's my code:

class AllFlights extends StatefulWidget {
  const AllFlights({Key? key}) : super(key: key);

  @override
  _AllFlightsState createState() => _AllFlightsState();
}

class _AllFlightsState extends State<AllFlights> {

  Future<void> getAllFlights() async {
    try {
      log("here");
      final res = await http.get(Uri.parse("http://192.168.8.100:5050/iflive/atc")); //fetch data -- gets stuck here
      log(res.body); // "log" statement, imported from dart:developer

    } catch (e) {
      log(e.toString());
    }
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: ElevatedButton(child: Text("All Flights",), onPressed: getAllFlights,),
      ),
    );
  }
}

Note: if it matters, the web server is running in a Docker container on port 5050 mapped to port 5050 on the host.

EDIT: I just noticed that a solid 2-3 mins after calling the api, it gives me a Socket Exception: [log] SocketException: OS Error: Connection timed out, errno = 110, address = 10.0.2.2, port = 44046

Is this normal?

1 Answers

Update: I was able to fix this by using adb (Android Debug Bridge) .

adb reverse tcp:5050 tcp:5050

this command routes your phone's requests on port 5050 to your computer's port 5050. Now you can just make requests to localhost directly instead on your computer's IP. The first port argument is your phone's port and second is your computer's.

example: adb reverse tcp:5000 tcp:5050 will map port 5000 on your phone to 5050 on your computer.

Have a nice day everyone!

Related