skip to Main Content

In my case, I have a list which contains some data. I need to give each data to api one by one.There are also some ‘other functionalities’ that I am doing before each api call to give some data to the api request.So I have given a for loop, and in each iteration I have set in such a way that the ‘other functionalities’ will work first and then the api call. I have made use of async and await. but ‘for loop’ will not wait for the api to finish. it runs all its iteration completely, and only ‘other functionalities’ inside the loop will work for each time. the problem is api may lag in that case. and there could be data mismatches also since I am giving certain datas to the api from ‘other functionalities’. I would like to know if there is any better idea in flutter to do this so that the next iteration only starts after the ‘other functionalities’ and the api call.

When I tried my way, all the ‘other functionalities’ completed in the first time and the api was still running one by one. Also some api calls may get failed.

2

Answers


  1. You can perform Asynchronous functions in a for loop like this:-

    Future<void> processDataList(List<dataItem> dataList) async {
      for (var data in dataList) {
        // Perform other functionalities before the API call
        processedData = await performOtherFunctionalities(data);
    
        // Make the API call using `await` to wait for completion
        await makeApiCall(processedData);
      }
    }
    
    Login or Signup to reply.
  2. Sounds like you should be using the await Future.wait().

    Here’s flutter’s example:

    void main() async {
      var value = await Future.wait([delayedNumber(), delayedString()]);
      print(value); // [2, result]
    }
    
    Future<int> delayedNumber() async {
      await Future.delayed(const Duration(seconds: 2));
      return 2;
    }
    
    Future<String> delayedString() async {
      await Future.delayed(const Duration(seconds: 2));
      return 'result';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search