乐闻世界logo
搜索文章和话题

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

1个答案

1

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:

yaml
dependencies: 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:

dart
import '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:

dart
Future<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 localhost to refer to your development machine is typically acceptable. However, when testing on a physical device, localhost or 127.0.0.1 refers 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 as 192.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.xml to 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.

2024年8月5日 01:56 回复

你的答案