uploadProfilePicture method

Future<void> uploadProfilePicture(
  1. XFile imageFile
)

Uploads a profile picture for a user @param imageFile The image file to be uploaded @throws Exception if the user ID is null or if the upload fails

Implementation

Future<void> uploadProfilePicture(XFile imageFile) async {
  try {
    final userData = await controller.getUserData();
    final UserModel user = userData;

    // Ensure the user ID is valid
    if (user.id == null) {
      throw Exception('User ID is null');
    }

    // Define the storage path
    final storagePath = 'avatars/${user.id}';

    // Upload the file to Firebase Storage
    final uploadTask = await uploadFile(
      file: imageFile,
      storagePath: storagePath,
      contentType: 'image/jpeg',
    );

    if (uploadTask != null) {
      await uploadTask.whenComplete(() async {
        // Update the user's Firestore document with the download URL
        await userRepository.updateUserRecord(user.id!, {'profilePicture': storagePath});
      });
    }
  } catch (e) {
    // Handle errors (e.g., file not found)
    throw Exception('Failed to upload profile picture: $e');
  }
}