HTTP package native request queue

86 views Asked by At

I am developing an application with Flutter and I am using an HTTP packet for HTTP requests. I have this problem related to Wi-Fi connection. When a user clicks a button (such as a confirm button) that executes an HTTP POST request, there is a chance that the user will lose the Wi-Fi connection right then and there. Obviously, the application does not send the request and it still remains available for the button to be clicked again. Now, let's say the user has a Wi-Fi connection and clicks the button, the request is sent normally, but it sends two requests instead of one. My theory is that there is some kind of "request queue" and the first request (which has not been sent) remains in that queue, and when the second request is executed, the packet sends two requests instead of one. I'll really appreciate any kind of help and thanks for your time!

I tried some validations to reject similar requests but it doesn't work. I need to "clear" that queue and whenever the package needs to make a request send one instead of multiple requests.

This is how i make POST requests:

Future<dynamic> _postJsonData(
  String token, String endpoint, dynamic object) async {
try {
  final url = Uri.https(_urlBase, endpoint);
  final response = await http.post(
    url,
    body: object.toJson(),
    headers: {
      'Authorization': 'Bearer ' + token,
      'Content-Type': 'application/json'
    },
  );
  return response;
} catch (e) {
  return http.Response(
      "{'error': true, 'mensaje': 'Ocurrió un problema en el servidor, intente nuevamente más tarde'}",
      503);
}

}

1

There are 1 answers

0
lookdadnomilk On

I would approach the issue in one of 2 ways

  1. Timeout: http has a timeout extension e.g. http.post(...).timeout(Duration(seconds:1), onTimeOut: ()=>throw Exception()) http timeout the idea here is that you expect the post to have a response in within that timeframe, if not, then assume something is wrong and throw an exception, ideally a custom exception that you can catch and decide what action you want to do with that. Here is an example of a custom network expection:

    class CustomNetworkException implements Exception { @override String toString(){ return 'timeout error'; } }

  2. have an interceptor. a bit more complicated, so I'd advise just looking at some articles instead of me trying to explain it here. checkout inteceptors, so when ever you get no-connection, you reset the call entirely