Using the Dart http package in Flutter to connect to a local server (such as localhost:8000) is a common requirement, especially during development when interacting with local backend services. The following are the steps and considerations to achieve this:
1. Add Dependencies
Ensure that your Flutter project includes the http package dependency. Open your pubspec.yaml file and add:
yamldependencies: flutter: sdk: flutter http: ^0.13.3
Remember to run flutter pub get to install the new dependency.
2. Import the Package
In the Dart file where you perform HTTP requests, import the http package:
dartimport 'package:http/http.dart' as http;
3. Send Requests
Next, you can use the http package functions to send requests to localhost. Assuming your local server is running on localhost:8000 and has an API endpoint /data, you can do the following:
dartFuture<void> fetchData() async { var url = Uri.parse('http://localhost:8000/data'); try { var response = await http.get(url); if (response.statusCode == 200) { print('Server responded with: ${response.body}'); } else { print('Request failed with status: ${response.statusCode}.'); } } catch (e) { print('Caught exception: $e'); } }
4. Considerations
-
Differences between Emulator and Physical Device: When running the Flutter app on an emulator, using
localhostto refer to your development machine is typically acceptable. However, when testing on a physical device,localhostor127.0.0.1refers to the device itself, not your development machine. In this case, you need to use the local area network (LAN) IP address of your development machine, such as192.168.1.4. -
Special Configuration for Android Devices: For Android devices, if targeting API 28 or higher, you must add a network security configuration to
AndroidManifest.xmlto permit cleartext traffic, since the localhost development server typically does not use HTTPS. For example:Modify
android/app/src/main/AndroidManifest.xml:xml<application ... android:networkSecurityConfig="@xml/network_security_config"> ... </application>Then create
android/app/src/main/res/xml/network_security_config.xml:xml<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">localhost</domain> </domain-config> </network-security-config>
This completes the basic setup. You can now interact with the local server in your Flutter application using the Dart http package.