Flutter › Networking with HTTP & Dio

How should you properly handle a genuine network timeout and other common network errors, such as no internet connectivity, when making a request using either the http or Dio packages?

Intermediate

Answer

Both the http and Dio packages support properly configuring an explicit timeout duration for a given request, after which that particular request automatically fails with a genuine timeout error rather than continuing to wait indefinitely forever, and properly wrapping your network calls within a try catch block lets you correctly distinguish between several genuinely different specific kinds of failures, such as a genuine connection timeout, a complete lack of any internet connectivity at all, or the server itself genuinely returning an actual error response, letting you display an appropriately clear, genuinely helpful specific error message tailored to exactly what actually genuinely went wrong.
try {
  final response = await dio.get(url).timeout(Duration(seconds: 10));
} on DioException catch (e) {
  if (e.type == DioExceptionType.connectionTimeout) {
    showTimeoutError();
  }
}
Real-world example A news app properly configures a reasonable ten second timeout for its article fetching requests, displaying a genuinely clear, specific timeout error message rather than leaving the user staring indefinitely at a loading spinner that would otherwise simply never actually genuinely complete.

Common follow-ups: What genuinely reasonable timeout duration is generally appropriate for a typical mobile network request?;How do you actually properly and correctly detect whether a device genuinely currently has any internet connectivity at all before even attempting a given request?