How to check a specific Value in multiple Documents in Firestore with Flutter

230

Solution 1

Answer 3.0

Your answer lies in the following

  • Fetch the createdAt element from the DataSnapshot array which is allDocs
  • There is a catch that createdAt brings in the timestamp in the Firebase TimeStamp instance format, that is => TimeStamp(seconds=int, nanoseconds=int), for example: Timestamp(seconds=1593504718, nanoseconds=706167000)
  • What we care about is getting the seconds, which is nothing but a timestamp only
  • Use the seconds and get the Year from it, and store it in your yearDocs

To get the data in the form of year, we do this

allDocs.forEach((item) => print(item.data["createdAt"].seconds));

// gives your timestamp
// 1593504718
// 1593504699
// 1593259892
// 1596121191

We can get the year via doing this

new DateTime.fromMillisecondsSinceEpoch(1593504718 * 1000).year

Combining all of these, let us code:

  List documents = [];

  @override
  void initState() {
    Firestore.instance.collection('Collection').getDocuments().then((snapshot) {
       List<DocumentSnapshot> allDocs = snapshot.documents;
  
       // now here we get the data in respect of year
       List<DocumentSnapshot> yearDocs = allDocs.where((e) => 
          DateTime.fromMillisecondsSinceEpoch(e.data["createdAt"].seconds * 1000).year == DateTime.now().year).toList();
  
       print(yearDocs.length);
  
       // iterate over your yearDocs, and add the data to documents
       yearDocs.forEach((item){
         documents.add(item);
       });

       print(documents.length);
    });
  }

Rest will be fine, you can populate the data as per the documents.length. Please let me know if that helped you. :) This will also help you gain some insight => DateTime class

Solution 2

I think you’re missing data

yearDocs = allDocs.where((e) => e.data['createdAt'].toDate.year() == DateTime.now()).toList();
Share:
230
Kinnay
Author by

Kinnay

Updated on December 23, 2022

Comments

  • Kinnay
    Kinnay over 1 year

    I'm trying to check if any document from my collection contains a Value with a specificTime. But Im doing something wrong.

    Im searching for a way to check if any Document in my Collection contains the "DateTime.now().year" in the "CreatedAt" Field.

      List documents = [];
    
      @override
      void initState() {
        Firestore.instance.collection('Collection').getDocuments().then((snapshot) {
      List<DocumentSnapshot> allDocs = snapshot.documents;
      List<DocumentSnapshot> yearDocs = allDocs.where((e) => e.data['createdAt'].toDate.year() == DateTime.now().year).toList();
      // iterate over your yearDocs, and add the data to documents
      yearDocs.forEach((item){
        documents.add(item);
      });
    });
        super.initState();
      }
    

    I want to set a List with Documents where the "Field" contains the "DateTime.now().year". Then i check if the List is emtpty.

    documents.length >= 1? Container(
        child:  Text('works'),
      ) : SizedBox(),
    
    • Alok
      Alok over 3 years
      Could you help me with the error, you're getting?
  • Alok
    Alok over 3 years
    I guess, you're right lenz. But we are still unsure, what kind of error he is facing right now
  • Kinnay
    Kinnay over 3 years
    I improved my Code like it is in my Question, but the List is empty even when the year of "createdAt" matches the current year.
  • Alok
    Alok over 3 years
    Checkout my Improvements section @Kinnay and let me know if that helps
  • Alok
    Alok over 3 years
    There is the problem then, your data is not been able to fetched correctly. Let us debug line by line and then find out the solution. Are you up for that @Kinnay ? Also, I will be making my answer reflect only solution which will have to work for you. You can keep your code like yours, but make ammendments according to my provided code in your code.
  • Kinnay
    Kinnay over 3 years
    Year Docs are empty. I get these Errror:
  • Kinnay
    Kinnay over 3 years
    I/flutter (18109): 0 E/flutter (18109): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: Closure call with mismatched arguments: function 'year' E/flutter (18109): Receiver: Closure: () => DateTime from Function 'toDate':. E/flutter (18109): Tried calling: year() E/flutter (18109): Found: year() => DateTime
  • Kinnay
    Kinnay over 3 years
    all Docs isnt Empty, it has 5 Items
  • Alok
    Alok over 3 years
    Brilliant, could you get me the data of allDocs in print(allDocs);? Or something like this allDocs.map((element) => print(element)); @Kinnay
  • Kinnay
    Kinnay over 3 years
  • Alok
    Alok over 3 years
    @Kinnay I have answered your question with the final solution Answer 3.0, I hope that would help you in great extent. Please let me know
  • Alok
    Alok over 3 years
    Finally @Kinnay Hahaha! It was a mutual effort. Thank you for making me learn something new today. All the very best :)