Firestore Subcollections in Flutter
Firestore Subcollections in Flutter
Firestore Subcollections In
Flutter
Let's learn how to work with firestore subcollection in flutter
F
irebase is an amazing platform developed by Google to connect mobile
and web applications and help developers to improve, build, and grow
their apps. Firebase provides us a variety of products Authentication,
Realtime Database, Cloud Firestore, Cloud Storage, Cloud Functions,
Firebase Hosting, ML Kit. Firebase is highly effective and easy to use.
Table of content:
::What is subcollection?
To work with firebase cloud firestore in flutter you need to learn about basic
crud operation i.e. uploading data, deleting data, editing data, fetching
data.
What is subcollection?
Let's understand subcollection through an example, take an example of a
shopping application, in this app, there are two people 1st the user that will
place the order and the 2nd wander that will accept the user’s orders. For
each user, the wander needs to keep a record of every user’s order. So to
keep the data in a sequential manner we can create a subcollection in the
following manner.
***Subcollection example***
In the above image, you can easily analyze the user’s order in an easier and
precise manner. So to create this type of collection we need to specify the
documentId .
await FirebaseFirestore.instance
.collection('users')
.doc(userCredential.user.uid)
.set({
'username': username,
'email': email,
'laundryBagNo': laundryBagNo,
'image_url': url,
});
2. Now in the other application we will fetch the stream of users and
using the snapshot of the stream we will get all the userId i.e.
StreamBuilder(
stream:
FirebaseFirestore.instance.collection('users').snapshots(),
return userSnapshot.hasData
? ListView.builder(
itemCount: userSnapshot.data.documents.length,
DocumentSnapshot userData =
userSnapshot.data.documents[index];
if (userData
.data()['laundryBagNo']
.toString()
.startsWith('B-') &&
boys)
return UserCard(
userId: userData.data()['userId'],
userEmail: userData.data()['email'],
userName: userData.data()['username'],
userLaundryBagNo:
userData.data()['laundryBagNo'],
userImageUrl: userData.data()['image_url']);
else if (userData
.data()['laundryBagNo']
.toString()
.startsWith('G-') &&
girls)
return UserCard(
userId: userData.data()['userId'],
userEmail: userData.data()['email'],
userName: userData.data()['username'],
userLaundryBagNo:
userData.data()['laundryBagNo'],
userImageUrl: userData.data()['image_url']);
else
return SizedBox();
})
: CircularProgressIndicator();
},
),
Now we can access the subcollection that we have created named order
await FirebaseFirestore.instance
.collection('users')
.doc(userCredential.user.uid)
.set({
'username': username,
'email': email,
'laundryBagNo': laundryBagNo,
'image_url': url,
'userId': userCredential.user.uid
});
Creating a sub-collection:
orders is a collection that contains a document whose id is the userId that
we can easily get through FirebaseAuth instance using currentUser.
await FirebaseFirestore
.instance
.collection('orders')
.doc(user.uid)
.collection(
"user_orders")
.add({
});
Fetching a sub-collection:
To fetch orders subcollection we will need the documentId , so to get the
documentId we need to fetch the users collection to get the userId .
StreamBuilder(
stream:
FirebaseFirestore.instance.collection('users').snapshots(),
return userSnapshot.hasData
? ListView.builder(
itemCount: userSnapshot.data.documents.length,
DocumentSnapshot userData =
userSnapshot.data.documents[index];
if (userData
.data()['laundryBagNo']
.toString()
.startsWith('B-') &&
boys)
return UserCard(
userId: userData.data()['userId'],
userEmail: userData.data()['email'],
userName: userData.data()['username'],
userLaundryBagNo:
userData.data()['laundryBagNo'],
userImageUrl: userData.data()['image_url']);
else if (userData
.data()['laundryBagNo']
.toString()
.startsWith('G-') &&
girls)
return UserCard(
userId: userData.data()['userId'],
userEmail: userData.data()['email'],
userName: userData.data()['username'],
userLaundryBagNo:
userData.data()['laundryBagNo'],
userImageUrl: userData.data()['image_url']);
else
return SizedBox();
})
: CircularProgressIndicator();
},
UserCard is a widget that displays the user details and on taping it new
screen is pushed that contains all the orders of that particular user.
CurrentOrders({
@required this.userId,
});
@override
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('orders')
.doc(userId)
.collection('user_orders')
.snapshots(),
return orderSnapshot.hasData
? ListView.builder(
itemCount: orderSnapshot.data.documents.length,
DocumentSnapshot orderData =
orderSnapshot.data.documents[index];
return OrderItem();
},
: CircularProgressIndicator();
});
Updating sub-collection:
FirebaseFirestore.instance
.collection('orders')
.doc(userId)
.collection('user_orders')
.doc(orderData.id)
.update(
{'key': 'new_value'});
Deleting sub-collection:
FirebaseFirestore.instance
.collection('orders')
.doc(userId)
.collection('user_orders')
.doc(orderData.id)
.delete();
We welcome feedback and hope that you share what you’re working on
using #Flutter. We truly enjoy seeing how you use Flutter to build
beautiful, interactive web experiences!