Proper way of setting request timeout for Flutter http requests?
With the raw HttpClient
API from dart:io
, you can cancel an HTTP request by calling HttpClientRequest.abort
when your Future
times out:
import 'dart:async';
import 'dart:io' as io;
Future<void> main(List<String> args) async {
var slowUrl = args.first;
var httpClient = io.HttpClient();
var request = await httpClient.getUrl(Uri.parse(slowUrl));
try {
var response = await request
.close()
.then(
(_) => print('Got eventual response'),
)
.timeout(
const Duration(seconds: 1),
);
} on TimeoutException catch (_) {
print('Timed out');
request.abort();
}
}
When run with with an URL with a slow response, the above should print "Timed out" and not "Got eventual response".
However, HttpClientRequest.abort
is (as of writing) a somewhat recent addition, and currently it is not exposed in package:http
.
Comments
-
ch271828n over 1 year
I need to set a timeout for http requests.
I have read Set timeout for HTTPClient get() request and it suggests us to use
http.get(...).timeout(...)
.However, I am worried: that
.timeout
is a method inFuture
class. Therefore, even if it timeouts, the http request is still ongoing! In other words, if the http request actually needs, say, 30 seconds to finish, and we usetimeout(Duration(seconds: 5))
, then even if it seems as if we have aborted the request, it is actually still costing resources of the phone of the user for another 25 seconds.Therefore, I would appreciate it if there is a proper way to timeout requests. Or, please correct me if I am wrong.
P.S. I know there is another thing,
HttpClient.connectionTimeout
. That is for connecting phase, not the time of whole request. Interestingly, when I go into the source code see here, I find that it also usessome_future.timeout()
internally. Therefore, the resources, IMHO, are also not released when timeout.