Vinicius Morais
Vinicius Morais

Reputation: 595

How make local http request in flutter?

I'm making an app, and i already have a server running in my local. I can acess trought my navigator the url:

Request URL: http://localhost:4444/categorie?page_size=15&page=1
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:4444
Referrer Policy: no-referrer-when-downgrade

Preview:

{
    "count": 4,
    "next": null,
    "previous": null,
    "results": [
        {
            "uid": "_b656062d3754",
            "name": "Pinga"
        },
        {
            "uid": "_0c644473c244",
            "name": "Cerveja"
        },
        {
            "uid": "_75df557ccbaa",
            "name": "Vinhos"
        },
        {
            "uid": "_8e32ce3baded",
            "name": "Refrigerantes"
        }
    ]
}

But when i try in flutter, the request never respond:

getCategories() async {

  String url = 'http://localhost:4444/categorie?page_size=15&page=1';

  var response = await http.get(url);

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return response.body;
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

I'm running the server in my Windows10 using Django. And my flutter app is in the Android Studio using a Virtual Machine as device. I tryed to change the ip to 127.0.0.1 and 10.0.0.1 but still not working. Have i change the host of Django or enable any configuration in my flutter or inside VirutalBox?

My dependencies:

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  http: any

dev_dependencies:
  flutter_test:
    sdk: flutter

Upvotes: 1

Views: 2794

Answers (2)

Diwyanshu Rai sharma
Diwyanshu Rai sharma

Reputation: 121

Use this in pubspec file under dependencies:

http: ^0.12.0+2

Use this method for Http request

getCategories() async {
    final response = await http.get("http://localhost:4444/categorie?page_size=15&page=1",

      headers: {
        'content-type': 'application/json',
      },
    );

    if (response.statusCode == 200) {
      final result = json.decode(response.body);

      var list = result['results'] as List;
    //  make a model class
      List<Categories> categories_= list.map((i) => Categories.fromJson(i)).toList();
      setState(() => {
      // update value
      });
    } else {
 setState(() => {
       // Show error
      });

    }

  }

Model class:

class Categories{
  String uid;
  String name;

  Categories({this.uid, this.name});

  Categories.fromJson(Map<String, dynamic> json) {
    uid = json['uid'];
    name = json['name'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['uid'] = this.uid;
    data['name'] = this.name;
    return data;
  }
}

Upvotes: 3

J. S.
J. S.

Reputation: 9635

Your localhost on your PC is not the same on your Android emulator. To access your PC's localhost from the Android emulator, you need to point to 10.0.2.2.

This means that you need to change your code to:

String url = 'http://10.0.2.2:4444/categorie?page_size=15&page=1';

Upvotes: 5

Related Questions