18

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. This works fine too when I point to any real URL, such as https://example.com, but when I point to https://127.0.0.1:8000 I get an error like " connection refused "

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 please it's my first time with flutter ? PS: i'm running on my phone device , my pc and phone are connected with the same wifi, my network is private.

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';

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

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

class _MyHomePageState extends State<MyHomePage> {

  static const url = 'http://127.0.0.1:8000/api/membres/';

  // static const url = 'http://10.0.2.2:8000/api/membres/';
  //static const url = 'http://localhost:8000/api/membres/';
  //static const url= "192.168.1...:8000/association/api/membres";
  //static const url = 'https://jsonplaceholder.typicode.com/users';
  Future<List<Map<String, dynamic>>> _future;

  @override
  void initState() {
    super.initState();
    _future = fetch();
  }

  Future<List<Map<String, dynamic>>> fetch() {
    return http
        .get(url)
        .then((response) {
          return response.statusCode == 200
              ? response.body
              : throw 'Error when getting data';
        })
        .then((body) => json.decode(body))
        .then((list) => (list as List).cast<Map<String, dynamic>>());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          _future = fetch();
          setState(() {});
          return _future;
          },
        child: FutureBuilder<List<Map<String, dynamic>>>(
          future: _future,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Center(
                child: Container(
                  constraints: BoxConstraints.expand(),
                  child: SingleChildScrollView(
                    physics: AlwaysScrollableScrollPhysics(),
                    child: Text(snapshot.error.toString()),),),);}
            if (!snapshot.hasData) {
              return Center(
                child: CircularProgressIndicator(),
              );}
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index) {
                final item = snapshot.data[index];
                return ListTile(
                  title: Text(item['name']),
                  subtitle: Text(item['email']),
                );
              },
            );
          },
        ),
      ),
    );
  }
}

enter image description here

enter image description here

enter image description here

Yoss
  • 466
  • 2
  • 4
  • 13
  • 1
    check your laptop's local IP using the command `ipconfig` for Windows or `ifconfig` for mac/linux. Use that IP instead of localhost or 127.0.0.1. These address are loopback addresses for the devices they are being accessed from. – Ryosuke Apr 29 '19 at 17:30
  • Also the port in the error is not the server port that you are connecting to but the client port. This value changes every time because the system picks a random port from available ports to make the request. – Ryosuke Apr 29 '19 at 17:32
  • how to do it please ? i'm already have triedwith my ip adress but it return an error also `static const url= "192.168.1.102:8000/association/api/membres"; ` ==> No route to host, errno = 113, address=192.168.1.102 , port = 46862 – Yoss Apr 29 '19 at 17:39
  • are you using mac, windows or linux? – Ryosuke Apr 29 '19 at 17:40
  • i'm using windows and i've changed my network to private – Yoss Apr 29 '19 at 17:42
  • or just see [this](https://stackoverflow.com/a/4779992/10336633) and if it doesn't work then ask here. – Ryosuke Apr 29 '19 at 17:42
  • it doesn't work, – Yoss Apr 29 '19 at 22:25
  • check your phone and computer network you have to keep same network those then add computer ip address – Chanaka Weerasinghe May 09 '20 at 06:03

5 Answers5

42

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
11

You have to keep your mobile phone and computer same network connection.

then pass your url assuming your ip and url is this 192.168.1.102:8000

static const url= "192.168.1.102:8000/association/api/membres";
Chanaka Weerasinghe
  • 5,404
  • 2
  • 26
  • 39
2

Note: Please set your network as "Home Network". Setting the network as Home Network means that you are allowing your PC to share stuff with other devices on the same network.

If you are using Windows 10, this can be done with the following:

Open Settings Go to Network & Internet Select WiFi in the left menu Tap on the name of the connected WiFi Set the Network Profile of the network to be Private If you are having an issue, it is most likely to do with Windows Firewall.

Open Control Panel Go to Windows Defender Firewall Tap on Allow an app or feature through Windows Defender Firewall Check whether the app is enabled for Private networks (there should be a tick) If it is not enabled, tap Change settings and tick the checkbox under Private for the app

sid
  • 43
  • 6
2

In window 10 Open Settings go to network and internet setting after that click on Wifi on left side after that Click on your connected Wifi after that change Network Profile from public to private now your real devices will call apis you want to call from server

1

This one work for me (i use)

$: adb reverse tcp:8080 tcp:8080

scdev
  • 11
  • 1