Home > Software engineering >  How to retrieve the sorted amount using DocumentSnapshot
How to retrieve the sorted amount using DocumentSnapshot

Time:02-04

I store data to my firebase like this where the amt has years under it. And under the years has the months. Then under the months has amount.

uid1 > uid: uid1
     > amt:
       > 2021
         > 12
           > 500
       > 2022
         > 1
           > 100
         > 2
           > 50
uid2 > uid: uid2
     > amt:
       > 2021
         > 1
           > 250
         > 5
           > 5
uid3 > uid: uid3
     > amt:

How will I retrieve these information of uid with it's corresponding value for certain month. I wanted to use DocumentSnapshot but I don't have an idea if this is possible. Thanks!

For January 2022
uid2: 250
uid1: 100
uid3: 0

For February 2022
uid1: 50
uid2: 0
uid3: 0

CodePudding user response:

I do not know if you just want to retrieve a specific value for a specific month or build a widget with this data using a FutureBuilder. But to get the data use:

var documentReference = FirebaseFirestore.instance.collection(YOUR_COLLECTION_NAME).doc(SPECIFIC_UID);
var data = await documentReference.get();
var monthValue = (data.data() as Map)['amt'][SPECIFIC_YEAR][SPECIFIC_MONTH];

As an example for the uid1, year 2021 and month 1:

var documentReference = FirebaseFirestore.instance.collection(YOUR_COLLECTION_NAME).doc(uid1);
var data = await documentReference.get();
var monthValue = (data.data() as Map)['amt']['2021']['1'];

Also follow this link to the official Flutter Firebase docs for more info!

  •  Tags:  
  • Related