87

I'm following the Flutter Networking/HTTP tutorial to do a GET request to a server running on my localhost:8000. Visiting my localhost via my browser works fine. My code looks like this:

var url = 'http://localhost:8000';
Future<String> getUnits(String category) async {
    var response = await httpClient.get('$url/$category');
    return response.body;
}

This works fine when I point to any real URL, such as https://example.com, but when I point to https://localhost:8000 or https://localhost (or any variations of these), I get an error starting with:

E/flutter ( 4879): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 4879): SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 47060
E/flutter ( 4879): #0      IOClient.send (package:http/src/io_client.dart:30:23)

The port in the error above changes each time I reload the app. I looked in the http package code and it doesn't seem like there is a way to specify the port for the URL. How do I point to my localhost?

Mary
  • 18,347
  • 23
  • 59
  • 76
  • This might help https://docs.flutter.io/flutter/dart-core/Uri/Uri.http.html – Shady Aziza Nov 19 '17 at 07:02
  • for anyone having this issue on iis/express check this: https://stackoverflow.com/questions/58367151/bad-request-400-requesting-asp-net-core-3-0-from-flutter – mkb Oct 31 '21 at 05:42

13 Answers13

75

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.

Mary
  • 18,347
  • 23
  • 59
  • 76
38

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;
}
HamidReza
  • 1,726
  • 20
  • 15
  • 3
    this will work. But you have to make sure you add a binding to your locahost or you run your app on 192.168.1.102:8000 otherwise it will give “Bad Request-Invalid Hostname” When accessing localhost from emulators – Tharindu Jayasinghe Jul 15 '20 at 05:51
  • 1
    the new flutter will not accept strings for the url. you will need :: var url=Uri.parse(your_string_path) – Golden Lion May 12 '21 at 23:27
  • Hi, I am still having same issue after I tried to change the host to my ipv4 address or localhost or wifi ip... the issue still persists...Can you let me know how to fix it? not: using flask as backend –  May 20 '21 at 20:53
  • The Uri class also cannot parse IPv4 addresses in strings (frustrating!) – keysmusician Jul 06 '23 at 04:13
24

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

Seddiq Sorush
  • 2,709
  • 2
  • 20
  • 20
22

Try forwarding the port of your emulator or the device to your computers port

e.g if your server is running on localhost:8000 then run this command

adb reverse tcp:8000 tcp:8000

this command actually redirects your phone’s port 8000 to your computer’s port 8000.And now your client should be able to talk to the server running locally

Tip: this also works if you want to run your flutter web app on your phone locally using

flutter run -d web-server

more details here

Mahesh Jamdade
  • 17,235
  • 8
  • 110
  • 131
16

Short answer: You can pass an Uri instead of a string as parameter

      var client = createHttpClient();
      client.get(new Uri.http("locahost:8000", "/category"));
Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
  • I think httpClient.get can only take one input argument - I passed your answer in and it said `Too many positional arguments: 1 expected, but 3 found.` – Mary Nov 19 '17 at 23:50
  • 1
    Oh, you're using `createHttpClient` instead of `new HttpClient` my bad. Edited – Rémi Rousselet Nov 19 '17 at 23:59
  • 6
    That also resulted in the IO Error with a randomly chosen port. I think it usually would work, but I'm running the code in the Android emulator, which runs in a VM. So apparently I'm supposed to just point to 10.0.2.2 instead. – Mary Nov 20 '17 at 02:56
  • 2
    I am having the same error this is my code,I am able to get the response in the browser Future connect() async { var httpClient = new HttpClient(); var request = await httpClient.get('127.0.0.1', 3000, "/api"); var response = await request.close(); – Mahesh Jamdade Jan 27 '19 at 03:42
  • I believe the actual issues is caused by localhost reference on the Android emulator – Pavel Shastov May 31 '21 at 12:53
14

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 :)

jauki
  • 149
  • 1
  • 5
6

im using ubuntu 20LTS, laravel backend, flutter http package.

  • Step 1: in terminal run sudo apt-get install net-tools . this package supports ifconfig command to work.
  • Step 2: in terminal run ifconfig . then in the output search this line inet 192.168.43.217 netmask 255.255.255.0 broadcast 192.168.43.255 . then copy the inet 192.168.43.217 ip-address. also, note that ip-address will be different for you. for me it is 192.168.43.217 .
  • Step 3: goto your laravel project cd your_laravel_project and then run sudo php -S 192.168.43.217:81 -t public to serve to inet address.
  • Step 4: then from flutter static const _apiRoute = "http://192.168.43.217:81/api/login". huh!! this worked for me.
Lalith Kumar
  • 426
  • 1
  • 6
  • 10
6

if it is still not working even after pointing to 10.0.:2.2:port Most likely Android is not allowing the http traffic.

change the AndroidManifest.xml android/app/src/main

include

 android:usesCleartextTraffic="true" 

as shown below

<application
        android:name="io.flutter.app.FlutterApplication"
        android:label="app_name"
        android:icon="@mipmvvap/ic_vvlauncher"
        android:usesCleartextTraffic="true">
5

to find ip is ifconfig mac / linux

en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500


    this one => inet 192.168.43.57 netmask 0xffffff00 broadcast 192.168.43.255

    nd6 options=201<PERFORMNUD,DAD>
    media: autoselect
    status: active

start php

php -S 192.168.43.57:5000 index.php

than declare on future

Future<String> getIsi()async{
      final res = await new Dio().get('http://192.168.43.57:5000/lihat-isi');
      print('res.data');
      return res.data;
    }

an result is

I/flutter ( 3250): [{"id":"1","judul":"asasa","gambar":"asa","ket":"asa"},{"id":"2","judul":"asasa","gambar":"asa","ket":"asa"},{"id":"3","judul":"asasa","gambar":"asa","ket":"asa"},{"id":"4","judul":"asasa","gambar":"asa","ket":"asa"}]
malik kurosaki
  • 1,747
  • 15
  • 9
4

Localhost via the computer browser I assume?

Using "http://localhost:port" in the Flutter code points to the local emulator device and not the local server running on your coomputer.

Point url to the IP Address of your server machine instead, that should solve the issue.

Aditya
  • 51
  • 2
4

If your backend is on LARAVEL, make sure to serve the domain to your IP address and port before using it on your flutter application

To serve do this

php artisan serve --host=192.168.1.100 --port=8000

That should solve the problem.

kelrob-dev
  • 91
  • 1
  • 9
3

If you are trying to access localhost api through emulator, Change localhost to your IPV4 Address. And if you are running your api in Visual Studio set the app URL also to be IPV4 address. In my case I changed it from "localhost:5001" to 192.168.XX.XX:5001

if you don't change the backend it will return “Bad Request-Invalid Hostname” When accessing localhost from emulators

enter image description here

Tharindu Jayasinghe
  • 2,821
  • 1
  • 15
  • 15
  • Thanks, man it helped me a lot because while running the app on an emulator makes my pc slow and while running it on a real device it is working awesome I mean the app is running smooth and pc too. – Shoaib Khan Mar 09 '21 at 05:35
1

https://ngrok.com/download

Download ngrokand run ngrok http <your localhost URL> (Please run this command in same location where you are download ngrok.exe) EX ngrok http http://127.0.0.1:8000

After that you will get URL forwarder link like http://98b9-2402-4000-2380-c5a6-c5c9-86cf-ea4d-66af.ngrok.io and change your base URL to this.

That's it! Enjoy and happy coding!!