getProfilePicture method

Future<ImageProvider<Object>> getProfilePicture({
  1. String? userEmail,
})

Retrieves the public URL of a user's profile picture @param userEmail The email of the user whose profile picture is to be retrieved @return A Future that resolves to an ImageProvider for the profile picture @throws Exception if the user document is not found or if the profile picture path is invalid

Implementation

Future<ImageProvider> getProfilePicture({String? userEmail}) async {
  try {
    late final DocumentSnapshot doc;

    // Fetch the user's Firestore document
    if (userEmail != null){
      final querySnapshot = await firestore
          .collection('users')
          .where('email', isEqualTo: userEmail)
          .limit(1)
          .get();

      if (querySnapshot.docs.isNotEmpty) {
        doc = querySnapshot.docs.first;
      }
    } else {
      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');
      }
      doc = await firestore.collection('users').doc(user.id).get();
      if (!doc.exists) {
        throw Exception('User document not found for userId: ${user.id}');
      }
    }

    // Retrieve the profilePicture field (file path) from the document
    final profilePicturePath = (doc.data() as Map<String, dynamic>?)?['profilePicture'] as String?;

    if (profilePicturePath == null || profilePicturePath.isEmpty) {
      // Fallback to a default profile picture from assets
      return const AssetImage(tDefaultAvatar);
    }

    // Dynamically generate the download URL
    final ref = FirebaseStorage.instance.ref(profilePicturePath);
    final downloadUrl = await ref.getDownloadURL();

    if (downloadUrl.startsWith('http')) {
      final cachedImage = CachedNetworkImage(
        imageUrl: downloadUrl,
        placeholder: (context, url) => const Center(
          child: CupertinoActivityIndicator(
            color: tPrimaryColor,
          ),
        ),
        errorWidget: (context, url, error) => const Image(
          image: AssetImage(tDefaultAvatar),
        ),
      );

      return CachedNetworkImageProvider(
        cachedImage.imageUrl,
        cacheManager: cachedImage.cacheManager,
      );
    }
    // If the URL is not valid, return a default image
    return const AssetImage(tDefaultAvatar);
  } catch (e) {
    debugPrint('Error fetching profile picture: $e');
    return const AssetImage(tDefaultAvatar);
  }
}