Setting a timeout on an HTTP request in Flutter and Dart
TimeoutExceptionShort answer
Dart HTTP calls have no timeout of their own beyond the operating system's. Add .timeout(Duration(...)) to the request future and catch TimeoutException, set connectionTimeout on an HttpClient, or set connectTimeout and receiveTimeout in Dio. Note that Future.timeout does not cancel the request.
Fix it fast
1Find out which cause you have
Find which client your code uses, because each one sets its timeout differently.
grep -rn "http.get\|HttpClient()\|Dio(" lib/2Match what you see, then jump to its fix
- 1
The screen shows a spinner for minutes and no error appearsThe request future has no time limitFix - 2
SocketException while connecting to a host that is downdart:io HttpClient waits on a dead hostFix - 3
DioException of type receiveTimeout, or none at all because nothing is setDio is used with no timeouts setFix
- 1
What does the error look like?
TimeoutExceptionSocketExceptionDioException with type receiveTimeout
Cause 1 of 3
The request future has no time limit
1Check
A plain request waits as long as the system lets it.
grep -rn "await http\." lib/2Fix
Chain .timeout on the future and catch TimeoutException. Without onTimeout the future completes with that exception. The original request is not cancelled; its late result is ignored.
import 'dart:async';
import 'package:http/http.dart' as http;
try {
final res = await http
.get(Uri.parse('https://example.com/api'))
.timeout(const Duration(seconds: 10));
// use res
} on TimeoutException {
// show a retry message
}3Verify
Point the URL at a server that does not answer. The catch block runs after 10 seconds.
flutter runConfirmed by api.flutter.dev
Cause 2 of 3
dart:io HttpClient waits on a dead host
1Check
connectionTimeout is null by default, so the operating system's own limit applies. It only affects new connections made after it is set.
grep -rn "HttpClient()" lib/2Fix
Set connectionTimeout when you create the client. A SocketException is thrown when it passes. Combine it with Future.timeout for slow responses.
final client = HttpClient()
..connectionTimeout = const Duration(seconds: 5);3Verify
Request an address that does not answer and count the seconds until the error.
flutter runConfirmed by api.flutter.dev
Cause 3 of 3
Dio is used with no timeouts set
1Check
Dio has its own timeouts on BaseOptions. receiveTimeout and sendTimeout throw a DioException of the matching type.
grep -rn "BaseOptions" lib/2Fix
Set the timeouts once on the shared instance and catch DioException.
final dio = Dio(BaseOptions(
baseUrl: 'https://example.com',
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 3),
));
try {
await dio.get('/api');
} on DioException catch (e) {
if (e.type == DioExceptionType.receiveTimeout) {
// show a retry message
}
}3Verify
Call a slow endpoint and see the catch branch run.
flutter runConfirmed by pub.dev
How do I stop it coming back?
- Give every network call a limit, set in one shared client.
- Show a retry button instead of a spinner without end.
- Remember Future.timeout stops waiting but leaves the request running.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- Qist BazaarA buy-now-pay-later marketplace built from a blank repo, now past 100K downloads on Google Play.
- SessionBirdAn omnichannel engagement suite in Flutter: campaigns, chatbot, tickets, analytics and live calling.
Related fixes
Mobile apps
Dio throws 'status code of 404 and RequestOptions.validateStatus' in Flutter
This exception was thrown because the response has a status code of 404 and RequestOptions.validateStatus was configured to throw for this status code.
Dio throws a DioException for any response outside 2xx and 304, and a 404 is one.
3 causes, each with a fixMobile apps
Dio requests fail with a connection or receive timeout in Flutter
DioExceptionType.connectionTimeout
Dio throws a DioException whose type says which timer ran out: connectionTimeout, sendTimeout or receiveTimeout.
4 causes, each with a fixMobile apps
Dio interceptor throws: the handler has already been called
Bad state: Future already completed
In Dio every interceptor callback gets a handler, and that handler may be completed only once.
2 causes, each with a fixMobile apps
A Dio request in Flutter fails with HTTP 405 Method Not Allowed
405 Method Not Allowed
405 means the server knows the URL but not the HTTP method you used on it.
2 causes, each with a fixMobile apps
Dio POST request ignores the headers you set
The server rejects the body because Content-Type is application/json, not application/x-www-form-urlencoded
Headers belong in Options for one request or in BaseOptions for the whole Dio instance, never in the data map.
3 causes, each with a fixMobile apps
Flutter Dio throws a bad response error with status 422
Unhandled Exception: DioError [DioErrorType.response]: Http status error [422]
A 422 is not a Dio fault.
3 causes, each with a fix