Kinnay
Kinnay

Reputation: 89

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

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(),

Upvotes: 2

Views: 394

Answers (2)

Alok
Alok

Reputation: 9008

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

Upvotes: 1

lenz
lenz

Reputation: 2425

I think you’re missing data

yearDocs = allDocs.where((e) => e.data['createdAt'].toDate.year() == DateTime.now()).toList();

Upvotes: 1

Related Questions