1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] How to fetch user from Firebase Firestore that is distinct of the currently logged...

Discussão em 'Mobile' iniciado por Stack, Outubro 17, 2024 às 23:02.

  1. Stack

    Stack Membro Participativo

    ``I am using SwipableStack package in Flutter to show images of every user (distinct than currently logged in) and swipe them and go to the next user image to swipe and show their profile images one by one on SwipableStack. But somehow, the image is always the same.`

    Here is my function for getting random user, it fetches random user from Firestore and then I am using users uid to get image from Storage in format "uid.jpg":

    try {
    final currentUser = FirebaseAuth.instance.currentUser;
    final currentUserId = currentUser?.uid;

    if (currentUserId == null || currentUserId.isEmpty) {
    print("Error: Current user ID is null or empty.");
    return null; // Exit early if the user ID is invalid
    }

    Query query = FirebaseFirestore.instance
    .collection('Users')
    .where('uid', isNotEqualTo: currentUserId)
    .limit(1); // Fetch one user at a time

    if (lastDoc != null && lastDoc.exists) {
    query = query.startAfterDocument(lastDoc); // Pagination if needed
    }

    QuerySnapshot querySnapshot = await query.get();

    if (querySnapshot.docs.isNotEmpty) {
    DocumentSnapshot randomUser = querySnapshot.docs.first;
    setState(() {
    lastFetchedUser = randomUser; // Update pagination reference
    });

    String imageUrl = "";
    List<String> tempUrls = [];

    if (randomUser['uid'] != null && randomUser['uid'].isNotEmpty) {
    Reference storageRef = FirebaseStorage.instance
    .ref()
    .child('user_images')
    .child('${randomUser['uid']}.jpg');

    try {
    imageUrl = await storageRef.getDownloadURL();
    print('Fetched image URL: $imageUrl'); // Debug print
    tempUrls.add(imageUrl);
    } catch (e) {
    print('Error fetching image URL for user ${randomUser['uid']}: $e');
    }
    } else {
    print('Invalid or missing UID for the user');
    }

    // Overwrite the image URL list and reset currentIndexImage
    setState(() {
    imageUrlList = tempUrls; // Overwrite with new image URL
    currentIndexImage = 0; // Reset to zero
    isLoading = false; // Update loading state
    });

    return randomUser; // Return the fetched user
    }
    } catch (e) {
    print('Error fetching user: $e');
    }

    return null; // Return null if no more users or an error occurred
    }````

    ` And Ui is like this, but I always get same user in Swipable Stack. The Item coount is always 1 to get one user at the time and I am getting images from Firebase Storage in format "uid.jpg"`

    ````@override
    Widget build(BuildContext context) {
    return Scaffold(
    body: Stack(
    children: [
    if (isLoading) // Show loading indicator if still loading
    Center(child: CircularProgressIndicator())
    else if (imageUrlList.isNotEmpty)
    SwipableStack(
    itemCount: 1, // Always show 1 item
    builder: (context, properties) {
    String imageUrl =
    imageUrlList[currentIndexImage]; // Always use index 0
    print('Displaying image: $imageUrl'); // Debug print

    return ClipRRect(
    borderRadius: BorderRadius.circular(60.0),
    child: Transform.scale(
    scale: 0.95,
    child: CachedNetworkImage(
    imageUrl: imageUrl,
    progressIndicatorBuilder:
    (context, url, downloadProgress) =>
    CircularProgressIndicator(
    value: downloadProgress.progress),
    errorWidget: (context, url, error) => Icon(Icons.error),
    ),
    ),
    );
    },
    onSwipeCompleted: (index, direction) async {
    setState(() {
    isLoading =
    true; // Show a loading indicator when fetching next user
    });

    print('Swiped $direction');

    await getRandomUser2(lastDoc: lastFetchedUser);

    setState(() {
    isLoading = false; // Hide loading indicator when done
    });
    },
    )````
    `

    Continue reading...

Compartilhe esta Página