You can tell it to use a fixed port and then that becomes the port you need to include in your allowed origins. Add --web-hostname=localhost --web-port=9999 as command line parameters to where you run your main. dart , then add localhost:9999 as an allowed origin.
Replacing the string localhost
with 10.0.2.2
resolved it for me, since I was running the code in the Android emulator, which is running in a VM. It's essentially a duplicate of this question.
replace 'localhost' in your url to wifi connection ip e.g : 'http://localhost:8000' => 'http://192.168.1.102:8000'. you can get your wifi ip from command prompt with cmd>ipconfig (wireless LAN adapter WI-FI.
var url = 'http://192.168.1.102:8000';
Future<String> getUnits(String category) async {
var response = await httpClient.get('$url/$category');
return response.body;
}
If you are using an Android emulator then localhost
on the emulator is not 127.0.0.0
it is 10.0.2.2
, so, on Android emulator you need to write https://10.0.2.2:8000
, the https://127.0.0.1:8000
will not work on real device too. because localhost
means something different on real device.
For more information on how to connect a Flutter app to localhost
on emulator or on a real device click on the link Connecting Flutter application to Localhost
Short answer: You can pass an Uri instead of a string as parameter
var client = createHttpClient();
client.get(new Uri.http("locahost:8000", "/category"));
I had the same problem, so apparently, I found a solution for this problem, so because you are in a virtual environment with your phone you cant use the localhost because the phone is not connected with your PC so simply, in my case, it worked, just use:
10.0.2.2:PORT
use this URL with your Port and it should work :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With