I’m working on a Flutter app that downloads a list of images when a button is clicked. I’m using the http.get()
method to download the images, but I’m facing an issue when the device is connected to a network without internet access. The http.get()
call seems to hang indefinitely, and it doesn’t throw any exceptions or return a timeout. Here’s what I’m experiencing:
-
When there is no internet, but the device is connected to a Wi-Fi network without actual internet access, the request doesn’t fail or throw an exception.
-
I’ve tried using
try-catch
,.onError()
, and checking the connectivity state with theconnectivity_plus
package. -
Despite the device losing internet access or switching to a network without internet, the
http.get()
call never reaches the error handler or timeout.
What I’ve Tried:
-
Checking the network state using
connectivity_plus
to see if the device is connected to Wi-Fi. -
Adding a
SocketException
handler to catch network-related errors. -
Using
.onError
with thehttp.get()
method to catch any exceptions.
import 'dart:io';
import 'package:http/http.dart' as http;
Future<void> downloadImage(String url) async {
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
// Image downloaded successfully
} else {
print('Failed to download image. Status code: ${response.statusCode}');
}
} on SocketException catch (e) {
print('No internet connection or network issue: $e');
} catch (e, stackTrace) {
print('Error downloading image from $url: $e');
print('Stack trace: $stackTrace');
}
}
Problem:
-
No exception or error is caught when the device is connected to a network without internet. The app just gets stuck on the
http.get()
call. -
I need to be able to detect the lack of internet access while still connected to a network and update the UI accordingly.
Question:
How can I ensure that http.get()
throws an exception or handles the case where the device is connected to a network without internet access in Flutter? Is there a better way to detect this condition and break the download process?
Additional Info:
-
I’m using Flutter with the
http
package. -
I prefer not to use timeouts for the request.
-
I’m already using the
connectivity_plus
package to track network changes.
Any guidance or help would be appreciated!
2