connectionFactory property Null safety

void connectionFactory=(Future<ConnectionTask<Socket>> f(Uri url, String? proxyHost, int? proxyPort)?)

Sets the function used to create socket connections.

The URL requested (e.g. through getUrl) and proxy configuration (f.proxyHost and f.proxyPort) are passed as arguments. f.proxyHost and f.proxyPort will be null if the connection is not made through a proxy.

Since connections may be reused based on host and port, it is important that the function not ignore f.proxyHost and f.proxyPort if they are not null. If proxies are not meaningful for the returned Socket, you can set findProxy to use a direct connection.

For example:

import "dart:io";

void main() async {
  HttpClient client = HttpClient()
    ..connectionFactory = (Uri uri, String? proxyHost, int? proxyPort) {
        assert(proxyHost == null);
        assert(proxyPort == null);
        var address = InternetAddress("/var/run/docker.sock",
            type: InternetAddressType.unix);
        return Socket.startConnect(address, 0);
    }
    ..findProxy = (Uri uri) => 'DIRECT';

  final request = await client.getUrl(Uri.parse("http://ignored/v1.41/info"));
  final response = await request.close();
  print(response.statusCode);
  await response.drain();
  client.close();
}

Implementation

void set connectionFactory(
    Future<ConnectionTask<Socket>> Function(
            Uri url, String? proxyHost, int? proxyPort)?
        f);