Sub topic 2
Allowing network access on each platform
This chapter explains why a request that works on one Flutter target can fail on another, and which configuration each platform needs. It assumes you can add a package to pubspec.yaml, run a Flutter app on at least one emulator or simulator, and read an XML or plist file. The previous chapter covered how HTTP and REST work. The next one makes the first GET request.
Why the Dart code is not enough
Dart code that calls client.get(uri) looks the same on every target. The operating system or browser underneath it does not behave the same way. Each platform decides whether your app may open a network connection, and some also decide which kinds of connection are allowed.
The failures are often confusing. A debug build works, and the release build you send to testers has no network. A request to https:// works, and one to http:// is blocked without a clear message. The same code works on Android and fails in Chrome. All of these come from platform rules, not from your Dart code.
| Platform | Needs configuration for HTTPS? | Needs configuration for plain HTTP? | Main file |
|---|---|---|---|
| Android | Yes, the `INTERNET` permission | Yes, a cleartext exception (Android 9 and later) | `AndroidManifest.xml` |
| iOS | No | Yes, an App Transport Security exception | `Info.plist` |
| macOS | Yes, the network client entitlement | Same entitlement, plus ATS rules | `*.entitlements` |
| Web | No manifest, but the server must allow CORS | Blocked from HTTPS pages (mixed content) | Server configuration |
| Windows and Linux | No | No | None |
Add the package first
All the examples in this tutorial use the http package. Add it from your project folder:
flutter pub add httpThis adds a line such as http: ^1.2.0 under dependencies: in pubspec.yaml and downloads the package. The exact version number depends on the day you run the command.
Android
The INTERNET permission
Android apps need the INTERNET permission to open network sockets. Open android/app/src/main/AndroidManifest.xml and add the permission as a child of <manifest>, outside <application>:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:label="my_app"
android:icon="@mipmap/ic_launcher">
<!-- activities omitted -->
</application>
</manifest>Flutter's project template already puts this permission in android/app/src/debug/AndroidManifest.xml and the profile manifest. Those files only apply to debug and profile builds. The main manifest is used by release builds, and it does not include the permission by default.
This is the usual cause of "it worked until I built a release APK". Debug builds can connect because the debug manifest adds the permission. The release build has no permission, and every request fails with a SocketException (shown as ClientException with SocketException when you use the http package). Put the permission in the main manifest so all build types have it.
The INTERNET permission is a normal permission. Android grants it at install time, so the user sees no prompt and your code does not have to ask for it.
Cleartext HTTP
Since Android 9 (API level 28), apps block cleartext traffic, meaning http:// URLs, by default. A request to http://example.com/api fails even if you have the INTERNET permission. The best fix is to use HTTPS. If you must reach an HTTP server during development, allow cleartext only for that host with a network security config.
Create android/app/src/main/res/xml/network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">10.0.2.2</domain>
</domain-config>
</network-security-config>Then point the <application> element at it:
<application
android:networkSecurityConfig="@xml/network_security_config"
android:label="my_app"
android:icon="@mipmap/ic_launcher">You may see advice to set android:usesCleartextTraffic="true" on <application>. It works, but it allows plain HTTP to every host. The domain-scoped config above is safer, because a mistake in your code cannot send data unencrypted to an arbitrary server.
Reaching a server on your own computer
Inside the Android emulator, localhost means the emulator itself, not your computer. The emulator provides the special address 10.0.2.2, which forwards to the host machine's loopback interface. If your dev server listens on port 8080, use http://10.0.2.2:8080. A physical Android device cannot use this address. Use your computer's LAN address, or run adb reverse tcp:8080 tcp:8080 and then use localhost:8080 on the device.
iOS
iOS needs no permission for network access. It does enforce App Transport Security (ATS), which requires HTTPS with modern TLS settings for connections made through the system networking stack. The http package on iOS goes through dart:io, and in a Flutter app on iOS the ATS rules apply to its requests too, so an http:// URL is blocked unless you add an exception. Check for this on a real build, because behavior differs slightly across Flutter and iOS versions.
For development against a server on your local network, the narrowest option is NSAllowsLocalNetworking. Add it to ios/Runner/Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>This allows cleartext loads to unqualified host names, .local names and IP addresses, and leaves ATS enforced for everything else. If you need plain HTTP to one named domain, list it in NSExceptionDomains with NSExceptionAllowsInsecureHTTPLoads set to true. Avoid NSAllowsArbitraryLoads, which turns ATS off for the whole app. App Store review may ask you to justify it.
The iOS simulator shares your Mac's network, so localhost works there. On a physical device running iOS 14 or later, the system shows a local network permission prompt the first time the app contacts a device on your LAN. Your Info.plist should include NSLocalNetworkUsageDescription with a sentence explaining why.
macOS
A macOS Flutter app runs in the App Sandbox. The sandbox blocks outgoing connections unless the app has the network client entitlement. Without it, requests fail even though the same code works on Windows. Add the entitlement to both macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements:
<key>com.apple.security.network.client</key>
<true/>The debug file already contains com.apple.security.network.server, which Flutter needs for hot reload and the debugger. That entitlement allows incoming connections, not outgoing ones, so it does not replace the client entitlement. As on Android, forgetting the release file is the classic mistake: the app works under flutter run and fails in the build you ship.
Web
A Flutter web app has no manifest to edit. The browser makes the request, and the browser enforces the same-origin policy. A page loaded from https://app.example.com can only read responses from another origin, such as https://api.example.com, if that server opts in with Cross-Origin Resource Sharing (CORS) headers.
The server must answer with a header like this:
Access-Control-Allow-Origin: https://app.example.comFor requests with a JSON Content-Type or an Authorization header, the browser first sends an OPTIONS preflight request. The server must answer it with Access-Control-Allow-Methods and Access-Control-Allow-Headers entries covering what you send.
If CORS is missing, the http package throws a ClientException with the message Failed to fetch. This message does not say CORS was the cause, and the Dart exception has no details. The real reason appears in the browser's developer console. You cannot fix this from Dart. Your options are:
- Configure CORS on the API server, which is the correct fix when you control it.
- Route requests through a backend or reverse proxy on your own origin.
- For local experiments only, launch Chrome with web security disabled. Never rely on this for anything you ship.
Browsers also block mixed content. A page served over HTTPS cannot call an http:// API.
Windows and Linux
Desktop builds for Windows and Linux have no sandbox or permission layer by default. Network calls work as soon as the package is installed. If you package the Linux app as a Snap or Flatpak, that packaging format adds its own network permission (for example the network plug in Snap), but that is outside Flutter.
Choosing the host for local development
One helper keeps the host choice in a single place. This version works on web, Android and the other targets without importing dart:io:
import 'package:flutter/foundation.dart';
String get devHost {
if (kIsWeb) return 'localhost';
if (defaultTargetPlatform == TargetPlatform.android) return '10.0.2.2';
return 'localhost';
}
Uri devUri(String path) => Uri.http('$devHost:8080', path);On a physical Android device this returns the wrong host, so replace it with your computer's LAN address or use adb reverse as described above. Keep helpers like this out of release code, which should always use an HTTPS base URL from configuration.
Diagnosing a failure
When you change a manifest, plist or entitlements file, a hot reload or hot restart does not apply the change. Stop the app and run it again so the native project is rebuilt.
Exercise
Your app fetches data over HTTPS and works with flutter run on an Android phone. A tester installs the release APK and every request fails with a SocketException. What is the most likely cause, and where do you fix it?
Show answer
The INTERNET permission is probably only in the debug and profile manifests, which release builds do not use. Add <uses-permission android:name="android.permission.INTERNET" /> to android/app/src/main/AndroidManifest.xml, outside <application>, then rebuild the release APK.
Exercise
A macOS build of your app works from your IDE but fails after you build it for release. Which file did you most likely miss, and which entitlement does it need?
Show answer
macos/Runner/Release.entitlements is the likely miss. It needs com.apple.security.network.client set to true. The debug entitlements file already has the server entitlement and, in a typical project after you edited it, the client one, so the debug run works.
Exercise
Your Flutter web app gets ClientException: Failed to fetch from an API that works in Android and iOS builds. Can you fix it with a change in your Dart code? What should you do instead?
Show answer
No. The browser is blocking the response because the API server does not send CORS headers allowing your app's origin. Check the browser console to confirm, then add the CORS headers (including the preflight response) on the server, or send requests through a proxy on your own origin.