uploadMultipleToFirebaseStorage static method

Future<List<String>> uploadMultipleToFirebaseStorage({
  1. required String storagePath,
  2. Size compressSize = const Size(720, 1280),
  3. required List<String> filepathList,
  4. required void onError(
    1. String e
    ),
})

Uploads multiple images to Firebase Storage after compressing them.

The storagePath specifies the directory in Firebase Storage where the images will be uploaded. The compressSize parameter defines the maximum dimensions of the compressed images (default is 720x1280). The filepathList is a list of file paths to the images that need to be uploaded. The onError callback is called if any errors occur during the process, passing the error message as a string.

Returns a list of download URLs for the uploaded images. If any error occurs, an empty list is returned.

Implementation

static Future<List<String>> uploadMultipleToFirebaseStorage({
  required String storagePath,
  Size compressSize = const Size(720, 1280),
  required List<String> filepathList,
  required void Function(String e) onError,
}) async {
  try {
    final byteList = await Future.wait(
      filepathList.map((e) async => await File(e).readAsBytes()),
    );

    final compressedImages = await Future.wait(
      byteList.map(
        (bytes) async => await FlutterImageCompress.compressWithList(
          bytes,
          quality: 70,
          minHeight: compressSize.height.toInt(),
          minWidth: compressSize.width.toInt(),
          inSampleSize: 2,
        ),
      ),
    );

    final uploadTasks = compressedImages.map((data) {
      final ref = _storage
          .ref(storagePath)
          .child('${DateTime.now().microsecondsSinceEpoch}.jpeg');
      return ref.putData(data, SettableMetadata(contentType: 'image/jpeg'));
    }).toList();

    final snapshotList = await Future.wait(uploadTasks);
    final downloadUrls = await Future.wait(
        snapshotList.map((snap) => snap.ref.getDownloadURL()));

    return downloadUrls;
  } on FirebaseException catch (e) {
    onError('uploadMultipleToFirebaseStorage() ${e.message}');
    return [];
  } catch (e) {
    onError('uploadMultipleToFirebaseStorage() $e');
    return [];
  }
}