21
How to filter Documents in Cloud Firestore - #100DaysOfCode - Day 15
This post is part of my 100DaysOfCode series. In this series, I write about my 100DaysOfCode journey. My aim for this challenge is become proficient in flutter and firebase by building an Agriculture Management Information System.
On Day 13 we discussed how to pass data from a child widget to a parent widget.
In this post, we will discuss how to filter documents in firebase before making it a stream.
In context of our Agriculture Management System, we want a stream of all farmer documents, farmer documents within the same region as the current user only and farmer documents within the same district as the current user only.
First we created a getFarmerWhereFieldEqual()
method in my FarmerService()
class.
Stream<QuerySnapshot<FarmerServiceModel>> getFarmersWhereFieldEqual(
{required String field, required String condition}) {
return farmerRef
.where(
field,
isEqualTo: condition,
)
.snapshots();
}
This method accepts a string called field which specify the field to be filtered in the farmer document. It also accepts a string condition that specify what value the field need to be equal to.
class RegionFarmerCommand extends BaseCommand {
RegionFarmerCommand(BuildContext c) : super(c);
Stream<QuerySnapshot<FarmerServiceModel>> run() {
var condition = userModel.currentUser.region;
farmerModel.regionFarmers = farmerService.getFarmersWhereFieldEqual(
field: 'region', condition: condition);
return farmerModel.regionFarmers;
}
}
We created a RegionFarmerCommand()
that gets the current user region by calling userModel.currentUser.region
. We then call the farmerService.getFarmersWhereFieldEqual();
to get a stream of farmers within the same region as the current user. This stream is stored in the farmerModel.regionFarmers
property for future use and returned.
class DistrictFarmerCommand extends BaseCommand {
DistrictFarmerCommand(BuildContext c) : super(c);
Stream<QuerySnapshot<FarmerServiceModel>> run() {
var condition = userModel.currentUser.district;
farmerModel.districtFarmers = farmerService.getFarmersWhereFieldEqual(
field: 'district', condition: condition);
return farmerModel.districtFarmers;
}
}
This method is exactly like the RegionFarmerCommand().run() except that we get the current user district and filter on the district field.
In this post we discussed how to filter documents in firebase before before making it a stream.
Thank you for reading my post. Feel free to subscribe below to join me on the #100DaysOfCodeChallenge or connect with me on LinkedIn and Twitter. You can also buy me a book to show your support.
21