230👍
Harnish, 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
36👍
I went to the terminal and used ifconfig
command
I got my IP address: 192.168.0.109
Then I simply replaced this IP address with my "localhost" in flutter app http requests. And it worked like a charm!
- [Django]-How to get the current language in Django?
- [Django]-Django: Use of DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT in settings.py?
- [Django]-Embed YouTube video – Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'
15👍
- if in localhost instead localhost use the IP of your network
- hint:for find Ip in cmd run
ipconfig
and get the ipv4
1: Example:
await http.post("http://127.68.34.23/wp-json/...",
headers: headers,
body: json.encode(data))
if in server write the url of main in url
- [Django]-Django: Adding "NULLS LAST" to query
- [Django]-Django migrate –fake and –fake-initial explained
- [Django]-How to specify an IP address with Django test client?
14👍
I had the same problem running in a real device, and only changing the IP in API link doesn´t work.
The solution for me was to put the server run with the command below:
manage.py runserver 0.0.0.0:8000
Then pass your machine IP to the API link instead of localhost, as the sample below:
http://192.168.0.67:8000
- [Django]-Where is a good place to work on accounts/profile in Django with the Django registration app?
- [Django]-Authenticate by IP address in Django
- [Django]-Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
13👍
In addition to Rohan’s answer you can also read:
Unable to make calls to Localhost using Flutter, random port being assigned to HTTP GET call
I was trying to run my app on physical device using local server so, for that i had to use the below mentioned command, here keep in mind change the port number according to your own port number
adb reverse tcp:3001 tcp:3001
As @maheshmnj pointed that this command is redirecting your phone’s
port 3001 to your computer’s port 3001. In case if you want to
redirect port 2000 of your phone to port 3000 of your computer then
you could do thisadb reverse tcp:2000 tcp:3000
you can also read about adb and networking via going through below mentioned page
https://developer.android.com/studio/command-line/adb.html
- [Django]-Group by Foreign Key and show related items – Django
- [Django]-The QuerySet value for an exact lookup must be limited to one result using slicing. Filter error
- [Django]-Has Django served an excess of 100k daily visits?
8👍
This problem occurs when the endpoint are incorrect or your host and server backend (Example Laravel API)doesn’t share the same IP address.
Solution is.
- Connect your workspace (computer, emulator, devices) in the same
network. - Find your IP by typing on terminal
ifconfig
. - If you build your API with Laravel, start the server appointing to
IP ADDRESS
of your computer, sudophp artisan serve --host YOUR_COMPUTER_IP_ADDRESS --port NUMBER
Example:
`sudo php artisan serve --host 192.168.1.11 --port 80`
- Test your endpoint in Postman or similar Application and type
http://192.168.1.11:80/Your_Route
- If everything is working good, you can run with app. Go!!!
- [Django]-How to specify an IP address with Django test client?
- [Django]-Django datetime issues (default=datetime.now())
- [Django]-How to show a many-to-many field with "list_display" in Django Admin?
7👍
Try adding <uses-permission android:name="android.permission.INTERNET"/>
to your manifest. This solved this issue for me.
- [Django]-Django – how to visualize signals and save overrides?
- [Django]-Are Django SECRET_KEY's per instance or per app?
- [Django]-Django aggregate or annotate
6👍
I know that the question is too old, But I will answer this because this may be helpful to someone who has this problem.
Without more details, I can’t give a specific solution. But with following conditions can give a specific solution
- I imagine that the API host was in local computer
- I imagine that you use your emulator for running the app
The URL you tried with postman maybe something like this http://127.0.0.1:[port number]/register
or http://localhost:[port number]/register
. But this may not work with an emulator because it doesn’t have access to that URL. To get access to the local host of your you need to find out the host address.
Follow these steps to get your host address.
- Click on the three dots(More) in the android emulator
- Setting -> Proxy
- You can change your host address if you like by selecting `Manual proxy configuration
Then you can see your host name
with the port number
. Then replace your URL with those like http://10.0.0.2:5000/register
.
- [Django]-Django: Why do some model fields clash with each other?
- [Django]-How to concatenate strings in django templates?
- [Django]-Django Rest Framework remove csrf
5👍
In C#[.net core api], go to launchSettings.json under Properties tab and change the follwing code to this(change localhost to 0.0.0.0 on applicationURl) and on the app(flutter), use ur local IPV4 IP. ex: (192.169.0.10)
"coreWebAPI": {
"commandName": "Project",
"launchBrowser": false,
"launchUrl": "api/values",
"applicationUrl": "http://0.0.0.0:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
- [Django]-What is the SQL ''LIKE" equivalent on Django ORM queries?
- [Django]-What's the difference between ContentType and MimeType?
- [Django]-Error: No module named staticfiles
4👍
If you are using ‘localhost’ in your url, change it to your ipv4 address and it will work
- [Django]-Update all models at once in Django
- [Django]-Django removing object from ManyToMany relationship
- [Django]-How to manage local vs production settings in Django?
4👍
Soltuion that worked on my machine
[√] Flutter (Channel stable, 2.5.3, on Microsoft Windows [Version 10.0.19043.1288], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[√] Chrome - develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.61.2)
[√] Connected device (3 available)
STEP: 1 (get your ipv4)
in terminal/cmd type
ifconfig
for Mac/Linux/Unixipconfig
for Windows
you will get some result in windows it looks like
STEP: 2 (change your request url)
❌ Dont do
http.get('localhost/my-local-rest-api/etc'
127.0.0.1//my-local-rest-api/etc
.
✅ Do
- for android
http.get('10.0.2.2/my-local-rest-api/etc
- for ios
http.get('192.168.8.155/my-local-rest-api/etc
IMPORTANT
⚠ always pass Uri instead of raw String
example: http.get(Uri.parse('my-url-in-raw-string'))
STEP 3: enable un-encrypted networking connections
for Android
in android/app/src/debug/AndroidManifest.xml
<manifest ...other params...>
// STEP: 1 make sure you have INTERNET permission
<uses-permission android:name="android.permission.INTERNET" />
<application
android:label="YourAppName"
android:usesCleartextTraffic="true"> <-- STEP: 2 add this line
<activity
</application>
</manifest>
for iOS
in ios/Runner/Info.plist
add this
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
- [Django]-OneToOneField() vs ForeignKey() in Django
- [Django]-Mixin common fields between serializers in Django Rest Framework
- [Django]-Django logging of custom management commands
2👍
This is what I had to change to fix the same error in my case:
- Start django with
python manage.py runserver 0:8000
and not justpython manage.py runserver
(0:8000 is the abbreviation for 0.0.0.0:8000 and makes your web application visible on your local network – see https://docs.djangoproject.com/en/3.0/ref/django-admin/#runserver) - In your flutter app specify the server address using your pc local ip, i.e. instead of http://localhost:8000 use something like http://192.168.1.2:8000. To retrieve your current ip address run
ipconfig
in the terminal if on Windows, otherwiseifconfig
. - Update allowed host in django settings if necessary. For example set
ALLOWED_HOSTS = ['*', ]
(but only in your dev environment!)
- [Django]-Django template tag to truncate text
- [Django]-Get model's fields in Django
- [Django]-Gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> django
2👍
What you need to do is to get your public PC IP and use it in your URL for example:
http://192.168.0.67:3000, where 3000 is the port no.
- [Django]-How do I use CSS in Django?
- [Django]-Django – {% csrf_token %} was used in a template, but the context did not provide the value
- [Django]-Django select only rows with duplicate field values
2👍
For mac users to check ip address
in terminal type: ipconfig getifaddr en0
and use that Ip address as below
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:fluttertoast/fluttertoast.dart';
class AuthAction {
static String BASE_URL = 'http://192.168.0.105:27017/';
static Future<Null> signUpAction(
firstName, lastName, email, password, userName) async {
try {
http.Response res = await http.post( Uri.parse(BASE_URL + 'signUp' ));
print(res);
if (res.statusCode == 200) {
}
} catch (err) {
print(err);
// Fluttertoast.showToast(msg: 'err');
}
}
}
Note: I did not touch the port on which my mongo-node server is running. Which is 27017
- [Django]-Django Template Language: Using a for loop with else
- [Django]-Django Forms: if not valid, show form with error message
- [Django]-Django Reverse with arguments '()' and keyword arguments '{}' not found
2👍
Recently I also faced a similar issue, there are a few things you try and check (its applicable for both flutter or android with any backend language):
If you are testing on an android emulator
1.You should first get the ipv4 of your PC ( for mac type this in terminal ipconfig getifaddr en0)
-
Use this ip address in URI (hostname) while sending the request.
-
Go to Emulator settings -> proxy and select Manual proxy configuration and paste your PC ip address and port number as your local server port usually 3000.
-
Restart your emulator (this is necessary).
-
It should work, if it’s not working then restart your application and carefully check the whole URL. I am telling you this because I was passing extra ‘/’ before.
If you are testing on a physical device
- Make sure your device and PC are connected to the same network (using a mobile hotspot will be better).
- Get the ipv4 of your PC from the terminal and use this in URI (hostname) while sending the request.
- It should work, if it’s not then check your URL carefully.
- [Django]-Is it possible to pass query parameters via Django's {% url %} template tag?
- [Django]-Django request get parameters
- [Django]-(13: Permission denied) while connecting to upstream:[nginx]
2👍
Not the best solution in the world but a good workaround is to install ngrok and link your localhost to it. Worked fine for me and it’s very fast to setup.
- [Django]-How can I activate the unaccent extension on an already existing model
- [Django]-Where to put business logic in django
- [Django]-AssertionError: database connection isn't set to UTC
- [Django]-Django – Annotate multiple fields from a Subquery
- [Django]-Changing a project name in django
- [Django]-How do I get user IP address in Django?
1👍
I had the same issue in flutter with spring backend. Instead of using
‘http://localhost:8080/’ in my requests, I changed this to ‘http://143.235.7.641:8080/’ where ‘143.235.7.641’ is my Wi-Fi IPv4 address, and it worked.
(NOTE : I assume you are testing flutter in physical phone,and phone and computer are connected the same wi-fi.)
- [Django]-Django CSRF check failing with an Ajax POST request
- [Django]-How do I convert a Django QuerySet into list of dicts?
- [Django]-Exclude fields in Django admin for users other than superuser
- [Django]-Is it possible to pass query parameters via Django's {% url %} template tag?
- [Django]-How to update fields in a model without creating a new record in django?
- [Django]-Where does pip install its packages?
1👍
Title: Connecting Flutter App on Physical Device to Flask Server
Solution
Follow these steps to achieve the desired connection:
Run Flask Server:
Start your Flask server and make it accessible over the network using the following command:
flask run --debug --host 0.0.0.0
Find Your Machine’s IP Address:
Obtain your machine’s IP address (IPv4) by running the following command (on Ubuntu):
hostname -I
Replace localhost with this IP address in your Flutter app code.
Update Flutter App Code:
In your Flutter app, replace references to localhost with your machine’s IP address obtained in the previous step. Update the URLs or endpoints accordingly.
Example:
final serverUrl = 'http://your_machine_ip:5000/endpoint';
Connect Devices to the Same Wi-Fi Network:
Ensure that your physical device and your development machine (running the Flask server) are connected to the same Wi-Fi network.
Access the Flask Server from Flutter App:
Run your Flutter app on the physical device, and it should be able to access the Flask server using the updated IP address.
- [Django]-Using a UUID as a primary key in Django models (generic relations impact)
- [Django]-Django's SuspiciousOperation Invalid HTTP_HOST header
- [Django]-Django : How can I find a list of models that the ORM knows?
0👍
I had this same issue once,
After going through some overly complicated stackoverflow answers and google search, finally i figure it out,
In this case you are most likely to be using a android emulator, So just turn on the mobile data on the emulator then try it again, i’m sure that this time it will work.
- [Django]-Django Rest Framework pagination extremely slow count
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference
- [Django]-How to show a many-to-many field with "list_display" in Django Admin?
0👍
final response = await client.post(
"http://192.xxx.xx.xx/api/signin",
headers: {"Authorization": apiKey},
body: jsonEncode({
"username": username,
"password": password,
}));
Even I had got a SocketException Error but I replaced my IP address and didn’t mention any Port number and it worked for me, and if I mention the port number it would throw an error.
Hoping this would work out.
I am using Flask for backend ,using blocs.
- [Django]-What is pip install -q -e . for in this Travis-CI build tutorial?
- [Django]-Django – No module named _sqlite3
- [Django]-Using Django time/date widgets in custom form
0👍
Try ths link delay the fuction and your will not get this error
Future.delayed(const Duration(milliseconds: 500), () {
widget.callback();
});
- [Django]-FileUploadParser doesn't get the file name
- [Django]-How do you detect a new instance of the model in Django's model.save()
- [Django]-Uninstall Django completely
0👍
If you are running on real phone, then you will get this error even if you add your localhost address to allowed host.
For me, connecting my laptop to my phone’s hotspot and running django server with laptop’s ipv4 address (which you can find by using ipconfig command) by python manage.py runserver 192.168..:8000 i.e. your ipv4 address:port number, than you will be able to access django server using your phone’s browser as well, now add this your ipv4 address to your allowed host. And, change your url from localhost or 127.0.0.1 to your ipv4 address. I hope this resolves your issue.
- [Django]-Django Static files 404
- [Django]-Error when using django.template
- [Django]-Django admin: How to display the field marked as "editable=False" in the model?
0👍
Replace your URL with:
Uri.parse("YourURL").replace(host: "YourIPAddress");
Explanation: This error means your host-address isn’t correct (as already in above answers pointed out). As you probably have a physical device it must access the emulator server you hooked up to your computer (aka your IP adress).
How to get my IP-Adress?
MAC: ifconfig | grep "inet " | grep -Fv 127.0.0.1 | awk '{print $2}'
WINDOWS: netsh interface ip show address | findstr "IP Address"
- [Django]-Negating a boolean in Django template
- [Django]-How do I include related model fields using Django Rest Framework?
- [Django]-New url format in Django 1.9