Home > Software design >  How to retrieve the last added document in my Cloud Firestore collection, using Flutter?
How to retrieve the last added document in my Cloud Firestore collection, using Flutter?

Time:02-24

I am currently learning how to use Firebase and it is not too intuitive to me, yet. Basically, I would like to retrieve only the last document in my Cloud Firestore collection and save it as a Map<String, dynamic>. Here is my code:

  final _firestore = FirebaseFirestore.instance;

  Future<Map<String, dynamic>> fetchData() async {
    Map<String, dynamic> collection;

    try {
      QuerySnapshot<Map<String, dynamic>> data = await _firestore
          .collection('collection')
          .orderBy('timestamp', descending: true)
          .limit(1).get();

      collection = data;
    } catch (e) {
      print(e);
    }
    return collection;
  }

As of my understanding, the QuerySnapshot returns multiple DocumentSnapshots. I thought if I limit it to 1 and sort it by the generated timestamp I would be able to only get the last added document. However, I am unable to save my QuerySnapshot as a Map<String, dynamic> and could not find a way to make it work.

Many thanks in advance to those taking their time answering to this!

CodePudding user response:

Try this:

collection = data.docs.first.data() as Map;
  • Related