Flutter Bloc parellel image uploading

181 views Asked by At

I want to upload images in parallel while sending an event for each image

But Future.await doesn't work for me, I wonder if any solution?

Sample of my code

final proofs = _assetsMap.values.toList();
var isUploadedAll = true;
final waitingToBeUploaded =
    proofs.where((proof) => proof.mode == ThumbnailStatus.uploading);
for (final proof in waitingToBeUploaded) {
  final uploaded = await shipmentFacade.uploadDeliveryProof(
    asset: proof.asset,
  );

  yield uploaded.fold(
    (failure) {
      isUploadedAll = false;
      _updateProof(proof.asset, ThumbnailStatus.failed);

      return state.copyWith(
        proofs: _assetsMap.values.toList(),
      );
    },
    (proofDocument) {
      _updateProof(proof.asset, ThumbnailStatus.uploaded);

      return state.copyWith(
        proofs: _assetsMap.values.toList(),
      );
    },
  );
}

yield state.copyWith(
  proofs: _assetsMap.values.toList(),
  isUploading: false,
  hasUploadSuccess: isUploadedAll,
  hasUploadFailed: !isUploadedAll,
);
1

There are 1 answers

0
amorenew On

I used Stream.fromFutures

 final requests = <Future<ShipmentProofState>>[];
    final proofs = _assetsMap.values.toList();
    var isUploadedAll = true;
    final waitingToBeUploaded =
        proofs.where((proof) => proof.mode == ThumbnailStatus.uploading);

    for (final proof in waitingToBeUploaded) {
      requests.add(
        shipmentFacade
            .uploadDeliveryProof(
          asset: proof.asset,
        )
            .then(
          (uploaded) {
            return uploaded.fold(
              (failure) {
                isUploadedAll = false;
                _updateProof(proof.asset, ThumbnailStatus.failed);

                return state.copyWith(
                  proofs: _assetsMap.values.toList(),
                );
              },
              (proofDocument) {
                _updateProof(proof.asset, ThumbnailStatus.uploaded);

                return state.copyWith(
                  proofs: _assetsMap.values.toList(),
                );
              },
            );
          },
        ),
      );
    }
    
    yield* Stream.fromFutures(requests);