uploadFile method

Future<UploadTask?> uploadFile({
  1. required XFile? file,
  2. required String storagePath,
  3. String contentType = 'image/jpeg',
  4. Map<String, String>? customMetadata,
})

Uploads a file to Firebase Storage @param file The file to be uploaded @param storagePath The path in the storage bucket where the file will be stored @param contentType The content type of the file (default is 'image/jpeg') @param customMetadata Optional custom metadata to be associated with the file @return A Future that resolves to an UploadTask if the upload is successful, or null if no file was selected

Implementation

Future<UploadTask?> uploadFile({
  required XFile? file,
  required String storagePath, // Path in the storage bucket
  String contentType = 'image/jpeg', // Default content type
  Map<String, String>? customMetadata, // Optional custom metadata
}) async {
  if (file == null) {
    Helper.warningSnackBar(title: 'No file was selected');
    return null;
  }

  UploadTask uploadTask;

  // Create a Reference to the file
  Reference ref = storage.child(storagePath);

  final metadata = SettableMetadata(
    contentType: contentType,
    customMetadata: customMetadata ?? {'picked-file-path': file.path},
  );

  if (kIsWeb) {
    uploadTask = ref.putData(await file.readAsBytes(), metadata);
  } else {
    uploadTask = ref.putFile(File(file.path), metadata);
  }

  return Future.value(uploadTask);
}