uploadImage static method

Future<String?> uploadImage(
  1. File imageFile,
  2. String userId, {
  3. String? customPath,
})

Uploads a single image file to Firebase Storage under a user-specific path.

  • imageFile: The image file to upload.
  • userId: The user ID used to construct the storage path.
  • customPath: A custom storage path (optional). If provided, this will override the default path.

Returns the download URL of the uploaded image on success, or null on failure.

Implementation

static Future<String?> uploadImage(File imageFile, String userId, {String? customPath}) async {
  try {
    // Generate a unique filename based on the current timestamp
    String filename = DateTime.now().millisecondsSinceEpoch.toString();

    // Construct the storage file path
    String filePath = customPath ?? 'users/$userId/images/$filename$_imageExtension';

    // Check if running on web (unsupported for this method)
    if (kIsWeb) {
      throw UnsupportedError(_unsupportedErrorMessage);
    }

    // Upload the file to Firebase Storage
    UploadTask uploadTask = _storage.ref(filePath).putFile(imageFile);
    TaskSnapshot snapshot = await uploadTask;

    // Return the download URL of the uploaded file
    return await snapshot.ref.getDownloadURL();
  } catch (e) {
    debugPrint("Error uploading image: $e");
    return null;
  }
}