flutterdarthttpflutter-pub

How to handle HTTP API request while navigating pages quickly


For my scenario, I have used flutter http package to make http requests...In home screen I have to send around 3 http requests, Since I had to use await requests are sending one by one.

I have used BaseAPiService class so all the API calls will go though that,

If I Navigate to another place while above request happening how to destroy that connection? Otherwise if after navigate also app is waiting till previous API requests completed..

Sample base API service class used

class ApiService {
  apiGet(url, data) async {
  Get.dialog(LoadingDialog());
  var response;
  if (data == null) {
    response = await http.get(
    baseUrl + url,
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
  );
}
Navigator.pop(Get.overlayContext);
return response;
}

apiPost(url, data) async {
  FocusScopeNode currentFocus = FocusScope.of(Get.context);
  if (!currentFocus.hasPrimaryFocus) {
  currentFocus.unfocus();
  }
  Get.dialog(LoadingDialog());
  var response;
  if (data != null) {
   response = await http.post(baseUrl + url,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: data);
}
if (data == null) {
  response = await http.post(
    baseUrl + url,
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
  );
}
Navigator.pop(Get.overlayContext);
return response;
}
}

Solution

  • I found a solution

    To achieve this need to close the http connection when navigating, for do that need to make a client from http and need to close that client on dispose method

    var client = http.Client()
    var response = await client.get(url)
    

    close the connecton when navigating

    void dispose(){
      super.dispose();
      client.close()
    }