I’m creating a mobile application in Flutter that I’m testing on physical device(Android). I run my API on a wamp server in local. When I put the route in insomnia, it works and returns me a JSON. However, when I try from this routein my Flutter app. This gives me an error:
.
final httpResponse = await http.get(Uri.parse('$_baseUrl/motorlocations'));
I have tried :
http://127.0.0.1:80/...
http://localhost:80/…
http://10.0.2.2:80/...
http://myIPV4:80/…
=> If you look at the picture the port is 42794 while I entered port 80.
I’ve tried this command : adb -d reverse tcp:42794 tcp:80 (80)
but it isn’t working.
2
Answers
What do you see if you print _baseUrl?
The problem you’re encountering is related to how your Android device is trying to connect to your local server. When you use http://localhost,
http://127.0.0.1
, orhttp://10.0.2.2
, the Android emulator interprets these as references to the emulator’s own loopback network interface rather than your host machine’s local server. This is why you see a different port number.To solve this issue, you can use your host machine’s IP address instead. Follow these steps:
Find your host machine’s local IP address. You can use the command
ipconfig
in the command prompt (on Windows) orifconfig
(on macOS or Linux) to find it. Look for an IPv4 address (e.g.,192.168.1.x
).Use this IP address in your Flutter app’s code:
add Internet permission to manifest.xml
final String baseUrl = ‘http://your_host_machine_ip:80’;
final httpResponse = await http.get(Uri.parse(‘$baseUrl/yourAPI’));