So I have a method that uses the Flutter HTTP library and is responsible for calling HTTP requests to the server with code like this:
Future<List<DataModel>> fetchData() async { try { var url = Uri.parse('${baseUrlParse}myapipath'); var request = await http.get(url); var data = jsonDecode(request.body); return data; } catch (e) { print('Catch ${e}'); rethrow; } } This code runs fine and has no issues.
It got to the point where when I have no internet connection or server connection fails, the app freezes, and an error file appears (if you're debugging in VS Code), called http_impl.dart, and the error snippet goes something like this:
onError: (error) { // When there is a timeout, there is a race in which the connectionTask // Future won't be completed with an error before the socketFuture here // is completed with a TimeoutException by the onTimeout callback above. // In this case, propagate a SocketException as specified by the // HttpClient.connectionTimeout docs. if (error is TimeoutException) { assert(connectionTimeout != null); _connecting--; _socketTasks.remove(task); task.cancel(); throw SocketException( "HTTP connection timed out after $connectionTimeout, " "host: $host, port: $port"); } _socketTasks.remove(task); _checkPending(); throw error; }); I have tried to implement from this source and this, but when I make a request but have no connection, this error still occurs.
How to deal with this problem?
What I want is, if there is a problem with HTTP either there is no connection, or it fails to contact the server, then I can make a notification..
Is there something wrong with my code? Please help, thank you