Home > Enterprise >  Can't get one document from flutter cloud firestore
Can't get one document from flutter cloud firestore

Time:12-02

I'm trying to get one document by user id from firebase cloud firestore using flutter. I tried firstly to fetch the data then added a condition to it, but i'm not able to display the data or even print it in the console!

Here is what i've tried so far:

database.dart:

Future<DocumentSnapshot?> getFileByUser(String userId) async {  
    return FirebaseFirestore.instance  
        .collection('cartesPro') 
        .where('cartUserId', isEqualTo: FirebaseAuth.instance.currentUser!.uid)
        .get()
        .then((value) {
      value.docs.forEach((element) {
        print(element.id);  
      });   
    });
  }

ui page:

User? user = FirebaseAuth.instance.currentUser;

  showFile() {
    final files = DatabaseMethods().getFileByUser(user!.uid);
    print(files);
  }

and then made the call in a button so I can print the result only! it's returning the documents of the actual user, but I couldn't map the result in order to get the latest in timestamp order! I appreciate any kind of help, thanks in advance!

CodePudding user response:

If you want to get the most recent document for the user, you should order on the field that has the timestamp and the limit to a single result:

FirebaseFirestore.instance  
    .collection('cartesPro') 
    .where('cartUserId', isEqualTo: FirebaseAuth.instance.currentUser!.uid)
    .orderBy('timestamp', descending: true)
    .limit(1)
    .get()

See the Firestore documentation on ordering and limiting data for more on this.

CodePudding user response:

FirebaseFirestore.instance  
    .collection('products') 
    .where('cartId', isEqualTo: FirebaseAuth.instance.currentUser!.uid)
    .orderBy('timestamp', descending: true)
    .limit(1)
    .get();
  • Related