Home > Mobile >  Network foor loop async
Network foor loop async

Time:10-15

I want to a lot of request in for loop.This is my network method.

Future postdata<T, F extends ApiResponseFromJson>({
        @required T? requestmodel,
        @required F? responsemodel,
        @required String? path,
      }) async {
        try {
          final response = await dio.post(path!, data: requestmodel);
          print(ApiPath.API_URL   path);
          if (response.data is List) {
            return List<F>.from(
                (response.data).map((e) => responsemodel!.fromJson(e)));
          }
          return responsemodel!.fromJson(response.data);
        } on DioError catch (e) {
          final errorMessage = DioExceptions.fromDioError(e).toString();
          showSnackBarDialog("Hata", errorMessage, const Icon(Icons.error))
};



 List<CarModel> carModel=[CarModel(),CarModel(),CarModel()...]


 Future<ResponseModel?> postData(int index) async {
    responseModel.carModel = carModel[i];
    responseModel= await _networkService
        .postdata<RequestModel, ResponseModel>(
            requestmodel: requestModel,
            responsemodel: ResponseModel(),
            path: ApiPath.API_DATA_LINK); 

    return responseModel;
  }


 _allListModel() async {
        for (var i = 0; i < carModel.length; i  ) {
          differentList.add(await postData(i));
        }
 

I have different list and i need request list of lenght.But in for loop response always waiting the other index. But i dont need wait. Cause networkModel goes to list of lenght different API and i don't know which one result is coming to first.

I want to request in for loop and i don't need to the other index. How can i do ?

CodePudding user response:

This code call all request at once, just remove await and the method then is called when request end:

_allListModel() {
      for (var i = 0; i < carModel.length; i  ) {
        postData(i).then((value) {
          differentList.add(value);
        });
      }
    }

CodePudding user response:

You should use Future.wait to wait for multiple futures. You start all of them and then you wait until all are done and add all the results to the list.

Future<void> _allListModel() async {
  var futures = <Future<>>[]
  
  for (var i = 0; i < carModel.length; i  ) {
    futures.add(postData(i));
  }

  var responses = await Future.wait(futures);

  differentList.addAll(responses);
}
  • Related