How to point to localhost:8000 with the Dart http package in Flutter?

In this blog post, we will explore how to resolve a common issue when using the Dart http package in Flutter applications. Specifically, we will look at how to point to localhost:8000 and overcome any challenges that may arise.

The Problem

When working on a Flutter project that involves making HTTP requests using the Dart http package, developers often encounter issues when trying to access resources running on their local machine. Specifically, the string localhost does not always resolve to the expected IP address.

The Solution: Replacing localhost with 10.0.2.2

For those who are running their code in an Android emulator, a simple yet effective solution is to replace the string localhost with 10.0.2.2. This works because the Android emulator is essentially a duplicate of this question. By doing so, you can resolve the issue and ensure that your HTTP requests are made successfully.

An Alternative Solution: Replacing localhost with Your WiFi Connection IP

Another approach to resolving this issue is to replace localhost in your URL with your WiFi connection IP address. This can be achieved by running the command ipconfig (wireless LAN adapter WI-FI) on your Command Prompt and getting your WiFi IP address.

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

Example Use Case

To illustrate this concept, let’s consider a simple example of making an HTTP request using the Dart http package in Flutter.

import 'package:http/http.dart' as http;

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

Conclusion

In conclusion, resolving the issue of pointing to localhost:8000 with the Dart http package in Flutter can be achieved through several methods. By replacing localhost with 10.0.2.2, your WiFi connection IP address, or using a combination of these approaches, you can successfully make HTTP requests to resources running on your local machine.