runWithRealNetworkHttpClient<T> function
Runs package:http convenience calls and dart:io calls with real clients.
The test binding installs an HttpOverrides in its zone, but package:http convenience methods can use a zone-scoped Client instead of consulting HttpOverrides. Installing both here keeps application and host callbacks on the same real-network path.
Implementation
Future<T> runWithRealNetworkHttpClient<T>(Future<T> Function() callback) {
final client = IOClient(createRealNetworkHttpClient());
// Flutter's test binding installs a global fake HttpOverrides that returns
// HTTP 400 for every request. The zone override below covers work started in
// this callback, but Flutter image streams can start their NetworkImage
// request from a binding-owned async callback in the root zone. Temporarily
// replace the binding override as well so those requests reach the network.
// Restore it even when the test fails; the runner executes multiple attempts
// in the same isolate.
final previousGlobalOverride = HttpOverrides.current;
HttpOverrides.global = _RealNetworkHttpOverrides();
return HttpOverrides.runZoned(
() async {
try {
return await http.runWithClient(callback, () => client);
} finally {
try {
client.close();
} finally {
HttpOverrides.global = previousGlobalOverride;
}
}
},
createHttpClient: createRealNetworkHttpClient,
);
}