Flutter & Firebase with Multiple queries and Multiple collections
Before Starting please connect your flutter application with firebase by following the link below, official documentation for integrating your flutter app whether android or ios with firebase.
I hope you have completed your firebase integration. but if you are having any problem you can follow this CodeLab tutorial also
Suppose you have two collections users and products in your Database in the pattern given below and you would like to retrieve the purchase history of a customer.
we have a collection of “users” within that contains a document of user_id’s and then within that, we have a “products” collection with a document that contains the product_id. Now we want to gather the product id’s for the selected user and then retrieve the product price from the products collection in a list. ok if you are familiar with SQL database we use the concept of join there to achieve such task but Firestore Database is a NoSQL database and we don't have any concept like joins here which make these task more complicated.
But we are going to achieve these in flutter using nested future builder inside a stream builder it is a convenient and easy method from most of the other ways of solving such problems in a flutter.
First, we need a stream builder which will contain queries of users collection as stream and a has a child listview.builder.Inside Listview.builder we have a List of type DocumentSnapshot named products that contain data of our products collection (easy to understand) and we have a child ProductpriceListwhich takes index and list of document snapshot p_list as arguments.
Now let's explore ProductpriceList. ProductpriceList is a statelessWidget which contains a Future Builder and has a query of products collection as the future stream. We are accessing users products collection fields by “p_list[index][field name]” as p_list is the list of DocumentSnapshot.
I tried to show the easiest and direct way of solving this problem but you can create model class and functions for streams to make your code more effective.
Hope You Like it if yes then, please appreciate it by a clap : )
Thank You…..