Home > OS >  How to ignore previously requested API if requested multiple times
How to ignore previously requested API if requested multiple times

Time:07-30

I'm using HTTP requests to process API in my flutter app. I implemented API for searching for a product and once a response is got it will be shown on my UI. My problem is the API that was requested will return at a different time means if I am searching 'sweets' if I entered 's' it will start an API request with searching 's', and after entering 'so' it will send another API call, But the 'SW' response may come firstly from the server before reaching 's' result. It will replace the exact result that I need to display in my app. How to prevent this issue?

CodePudding user response:

You can handle it by filtering your response through your input. For example, if the incoming response is for "sw" and the user has already typed just the "sw" mark it with a boolean to "true" and ignore the further responses, or else if the incoming response is for "s" but the user has typed "sw" mark its boolean to "false" and ignore it and don't let it to replace your previous data.

You can define this boolean in your object model by the way.

CodePudding user response:

What I understood is that you have a textfield and you are trying to call an API inside onChanged function and you want give the user some time to see results before entering new characters. You have two options:

  1. Using timer that delays the call some seconds on every call.
  2. Using TextEditingController instead of relying on onChanged. And then you call the API inside the onSubmitted function.
  • Related