How to handle HTTP API request while navigating pages quickly

2.7k views Asked by At

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;
}
}
2

There are 2 answers

1
s.am.i On BEST ANSWER

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()
}
0
Rahat On

If you are deep into your code and don't have any handler for http.Client. And you don't want the latest response to be shown on the UI. then you can follow this approach.

We cant cancel a future in Dart but we sure can stop listening to a stream. And here is the catch we can convert the Future to a stream and stop listening for it if you want to cancel the Future.

void main() {
    // keep a reference to your stream subscription
    StreamSubscription<List> dataSub;

    // convert the Future returned by getData() into a Stream
    dataSub = getData().asStream().listen((List data) {
    updateDisplay(data);
  });

  // user navigated away!
  dataSub.cancel();
}

taken for here