How to Set a Proxy in Flutter and Dart: HttpClient and Dio

Published:

10 minute read

Acar Diveroli
Written by: Acar Diveroli
Two routes from a findProxy rule card: a blue route through a proxy node to the target, a dashed DIRECT route straight to it

In Dart, a proxy is defined by the findProxy function of the HttpClient object in the dart:io library. For each request, this function returns a line in the PAC format browsers use: PROXY host:port or DIRECT. On mobile and desktop, package:http and Dio use the same HttpClient. The trap is a trailing ; DIRECT: if the proxy fails, the request silently goes out from your own IP. This post covers the line format, credentials, package:http and Dio setup, SOCKS5 and the limits of Flutter web.

The findProxy line format

findProxy is a function that takes the request address (Uri) and returns a string. The string is not a URL. Dart reads it with the rule browsers use in PAC scripts: PROXY host:port means a proxy, DIRECT means a direct connection. Several entries are separated by semicolons and tried from left to right.

dart
import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  final client = HttpClient();
  client.findProxy = (uri) => 'PROXY pr.proxynet.io:8000';
  client.addProxyCredentials(
    'pr.proxynet.io',
    8000,
    '',
    HttpClientBasicCredentials('user', 'pass'),
  );

  final request = await client.getUrl(Uri.parse('https://api.ipify.org'));
  final response = await request.close();
  print(await response.transform(utf8.decoder).join());
  client.close();
}

The line stays the same when the target is HTTPS. HttpClient sends the proxy a CONNECT request and sets up TLS inside that tunnel. No scheme is written: when it sees http:// in the line, Dart stops with an Invalid proxy configuration error. PROXY must be uppercase and followed by a space.

LineBehavior
PROXY pr.proxynet.io:8000Every request goes through the proxy
PROXY pr.proxynet.io:8000; DIRECTIf the proxy fails, the request goes direct
DIRECTNo proxy is used
http://pr.proxynet.io:8000HttpException, no request is sent

The second line is risky. In Dart's source code, a connection error moves on to the next entry in the list. If the proxy is down or the tunnel is rejected with a 407, the request goes out via DIRECT. The app keeps working, but your IP has not changed. If the proxy is mandatory, don't add DIRECT to the list.

Credentials

HttpClient takes the proxy password in one of two ways. The first is inside the line: PROXY user:pass@pr.proxynet.io:8000. The second is the addProxyCredentials call. Both send a Proxy-Authorization: Basic header to the proxy, in the CONNECT tunnel as well.

addProxyCredentials takes four values: host, port, realm and the credentials object. Matching is done by host and port. So the host and port here must be exactly the same as in the findProxy line. The realm is not used for matching, an empty string is enough. If you fetch the password from a vault at runtime, there is also the authenticateProxy callback. It is called when the proxy returns a 407, and if it returns true, the request is retried.

The difference shows up when the password has special characters. In URL form, @ is encoded as %40. We explained this rule in How to Read a Proxy URL. The findProxy line, however, is not decoded. Dart splits the line at the last @ and sends the password as is.

dart
// Password: pass@123
client.findProxy = (uri) => 'PROXY user:pass@123@pr.proxynet.io:8000'; // works
client.findProxy = (uri) => 'PROXY user:pass%40123@pr.proxynet.io:8000'; // 407

In the second line, the string pass%40123 reaches the proxy and the password fails. The username cannot contain :, because the split happens at the first :. If your password contains @, : or /, the simplest route is addProxyCredentials.

Environment variables

The default findProxy value of HttpClient is the HttpClient.findProxyFromEnvironment function. Even if you write nothing, Dart looks at the http_proxy, https_proxy and no_proxy variables. Uppercase names are read too, but if both are set, the lowercase one wins.

bash
export HTTPS_PROXY=http://user:pass@pr.proxynet.io:8000
export NO_PROXY=localhost,127.0.0.1
dart run bin/main.dart

The function strips the scheme at the start of the value and the path at the end, then turns the rest into a PROXY line. Credentials go into the same line. So the decoding rule above applies here too. If you leave out the port, Dart assumes 1080. Each entry in the NO_PROXY list is compared with the end of the host name.

If you want to supply the variables from your own configuration instead of the system, use the environment parameter:

dart
client.findProxy = (uri) => HttpClient.findProxyFromEnvironment(
      uri,
      environment: {
        'https_proxy': 'user:pass@pr.proxynet.io:8000',
        'no_proxy': 'localhost',
      },
    );

To turn the proxy off completely, the official docs suggest client.findProxy = null. On servers and in CI, environment variables are a practical route. In a mobile app these variables are not set, so write an explicit findProxy there.

package:http and Dio

On platforms other than the web, package:http uses IOClient. IOClient accepts an optional HttpClient. You set the proxy on this inner client and wrap it:

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

http.Client proxyClient() {
  final inner = HttpClient()
    ..findProxy = (uri) => 'PROXY pr.proxynet.io:8000'
    ..addProxyCredentials(
      'pr.proxynet.io',
      8000,
      '',
      HttpClientBasicCredentials('user', 'pass'),
    );
  return IOClient(inner);
}

Future<void> main() async {
  final client = proxyClient();
  final res = await client.get(Uri.parse('https://api.ipify.org'));
  print(res.body);
  client.close();
}

The rest of your code works with the http.Client interface, while top-level functions such as http.get don't see this client. Build the client once at app startup and pass the same object everywhere.

Dio takes the same HttpClient through an adapter. The createHttpClient callback of the IOHttpClientAdapter class must return a client:

dart
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';

final dio = Dio()
  ..httpClientAdapter = IOHttpClientAdapter(
    createHttpClient: () {
      final client = HttpClient();
      client.findProxy = (uri) => 'PROXY pr.proxynet.io:8000';
      client.addProxyCredentials(
        'pr.proxynet.io',
        8000,
        '',
        HttpClientBasicCredentials('user', 'pass'),
      );
      return client;
    },
  );

Dio's interceptors, timeouts and retry settings are not affected. The proxy only comes in at the connection layer. If your mobile app needs to look like a real home user in a given country, the exit IP can come from the Residential Proxy pool. The code stays the same.

SOCKS5 support

dart:io has no built-in SOCKS support. The findProxy line only recognizes PROXY and DIRECT entries, and writing SOCKS5 makes the client throw. Putting socks5:// in an environment variable doesn't help either: Dart strips the scheme and tries to speak HTTP to the SOCKS port.

The symptoms of this mismatch are familiar: the connection is reset or the request times out. The details are in What Happens When You Use SOCKS5 on an HTTP Proxy Port?.

If you really need SOCKS5, HttpClient has a connectionFactory hook. This hook lets you open the socket connection yourself. Packages on pub.dev such as socks5_proxy attach a SOCKS5 tunnel here. These packages are maintained by the community, not the Dart team. Review their code and latest release date before you use them.

For most jobs the shorter route is the HTTP port. The Proxynet SOCKS5 Proxy also carries UDP, but HttpClient only speaks HTTP over TCP. On the Dart side, an HTTP proxy leaves nothing missing.

Android, iOS and Flutter web

A Flutter app does not read the device's Wi-Fi proxy setting on its own. HttpClient only looks at environment variables. Android and iOS don't pass these variables to an app, so the request goes out directly. Dart's API docs say this plainly: the platform's native clients work with proxy and VPN settings, HttpClient does not.

Keep two needs apart. If the app must always go out through your proxy, write findProxy. If you want it to follow the user's system proxy, use the CupertinoClient from the cupertino_http package on iOS and the CronetClient from the cronet_http package on Android, through package:http.

The emulator adds one more detail. On the Android emulator, localhost is the emulator itself. You reach a test proxy running on your computer at 10.0.2.2. The Dio docs give the same warning: the proxy address is written relative to the device the app runs on, not your computer.

Flutter web has no dart:io. There, package:http uses BrowserClient and the browser sends the requests. The proxy is a browser or operating system setting and cannot be changed from code. The Dio docs also state that a proxy cannot be set on the web. If the same codebase also compiles to the web, put the HttpClient code in a separate file and load it only on native platforms with a conditional import:

dart
import 'client_web.dart'
    if (dart.library.io) 'client_io.dart';

Troubleshooting

Most errors can be read from the message. First, compare the address an IP echo service returns with and without the proxy. If the two addresses match, the proxy is not in play at all.

SymptomLikely causeFix
Invalid proxy configurationScheme or lowercase proxy in the lineWrite PROXY host:port
Proxy failed to establish tunnel (407 …)Password missing, wrong or encoded as %40Raw password or addProxyCredentials
407 although addProxyCredentials was calledHost or port differs from findProxyUse the same value in both places
Request works, but the IP is yours; DIRECT, a NO_PROXY match or no findProxy on mobileCheck the line and the environment
SocketException, connection refusedWrong port or a SOCKS portUse the HTTP proxy port

The general causes of a 407 and the header flow are in How to Fix HTTP 407 Proxy Authentication Required. The error arrives as HttpException or SocketException. package:http wraps transport errors in a ClientException. If a request hangs for a long time, set HttpClient.connectionTimeout so the error shows up right away when the proxy can't be reached.

The bottom line

Give HttpClient the PROXY host:port line, add the password with addProxyCredentials and pass the same client to package:http or Dio. On mobile, don't rely on the system proxy; on the web, the proxy is the browser's job. Above all, if the proxy is mandatory, don't add DIRECT to the line: when something fails, the request silently goes out from your own IP.

Sources

Frequently asked questions

Does Flutter use the device's Wi-Fi proxy setting?

No. The HttpClient in dart:io does not read the device's proxy setting; it only looks at environment variables such as http_proxy. Android and iOS don't pass these variables to the app. For a fixed proxy, write findProxy. If you want to follow the user's system setting, use native clients such as CupertinoClient on iOS and CronetClient on Android through package:http.

Does Dart HttpClient support SOCKS5?

No. The findProxy line only recognizes PROXY and DIRECT entries. If you put socks5:// in an environment variable, Dart strips the scheme and tries to speak HTTP to the SOCKS port. There are community packages that use the connectionFactory hook for SOCKS5. For most jobs the HTTP proxy port is enough and needs no extra package.

How do I write an @ in the password in the findProxy line?

As it is. Dart splits the line at the last @, so PROXY user:pass@123@pr.proxynet.io:8000 works. Don't encode it as %40, because the line is not decoded and the string %40 reaches the proxy. If the password also contains : or /, passing it separately with addProxyCredentials is the safest route.

How do I apply the proxy only to some addresses?

Check the uri.host value in the findProxy function. Return PROXY pr.proxynet.io:8000 if the target is on your list, DIRECT otherwise. The function is called for every request, so the rule can be as detailed as you like. With environment variables, you do the same with the NO_PROXY list. Its entries are compared with the end of the host name.

Can you set a proxy in Flutter web?

No. Flutter web has no dart:io, and the browser sends the requests. The proxy is a browser or operating system setting. The Dio docs also state plainly that a proxy cannot be set on the web. If you also compile the same code to the web, keep the HttpClient setup in mobile and desktop builds only, with a conditional import.

Is the proxy line written differently for HTTPS requests?

No. The line stays the same: PROXY pr.proxynet.io:8000. For an HTTPS target, HttpClient asks the proxy for a CONNECT tunnel and sets up TLS inside it. Credentials from the line or from addProxyCredentials are added to the CONNECT request too. If the proxy rejects the tunnel, you get a Proxy failed to establish tunnel error.

Ask ChatGPTAsk Claude