Flutter: How to add Sub-Collection in Document? Firebase

How to Create Collection Within Docs Flutter

In this post, we are going to see how to add a sub-collection within the document in Firebase, Flutter. We are particularly going to use the Firestore Database for this example.

Firstly, Please note the structure of the collection and documents:

> A Collection is a collection of documents and has no properties.
> A Document consists of properties/fields and can have collections within it.

So this is a blog app and the blog consists of the title, description, image URL, and author ID. (If you keep an image URL field you will need to validate it prior to loading, here’s my post resolving that issue). Now I want to add a feature of comments and for that, I want to create a collection within the blog item.


What we want to achieve?

Image showing the structure we want to achieve in cloud firestore in Flutter.
Image showing the structure we want to achieve

So my current firebase Database looks like this, within the “posts” collection there is a document with certain post-related fields. There can be multiple documents inside the “posts” collection representing multiple posts:

Image showing the cloud Firestore in Firebase, here no comments subCollection is created within the post document.
Image Showing how the data is structured in Firebase Cloud Database

The code to add and get Items from the posts collection is like this:

import 'package:cloud_firestore/cloud_firestore.dart';

CollectionReference postsCollection = FirebaseFirestore.instance.collection("posts");

Future<String> addBlog(Map<String,dynamic> fields)async{
DocumentReference ref = await postsCollection.add(fields);
// Required in Ahead Steps
return ref.id;
}

Stream<QuerySnapshot> getBlogs(){
return postsCollection.snapshots();
}

The following code shows how to add a collection named “comments” inside the post document. A important thing is that we must know the document ID of the item.

Note that "comments" is a collection and stores the comment(as document) within itself as documents. Think of comments as a folder and a comment as a file within the folder comments.

After we know the document ID we can easily access and add a comment as a document within the “comments” collection.

addComment(Map<String, dynamic> comment, String docID) {
    postsCollection.doc(docID).collection('comments').add(comment);
}

Stream<QuerySnapshot> getComments(String docID) {
    return postsCollection
        .doc(docID)
        .collection('comments')
        .snapshots();
}

Now we just need to use the functions and now we can easily create any number of collections within a document.

Map<String, dynamic> blogData = {
  "title": "abc",
  "description": "lorem ipsum",
  "authorID": "JohnDoe@1123",
};

Map<String, dynamic> commentData = {
  "authorID": "John Doe",
  "date": DateTime.now().millisecondsSinceEpoch,
  "text": "Hello guys"
};

void createPostWithComments() async {
  String docId = await addBlog(blogData);
  addComment(commentData, docId);
}

Result:

In this image we have added a sub-collection by the name of "comments" in the post document.
Image showing the complete structure of a sub-collection within a document

To retrieve the data you can use the getBlogs() and getComments(String) respectively. So we can easily create a collection within a document if we have the document ID. If you still have any queries you can let me know in the comments down below. If you are new to flutter check my post on how to install flutter on windows?

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
Validate ImageURL in Flutter

How to check if Image URL is valid in Flutter?

Next Post
How to use HexColor in Flutter

How to convert HexColor to Flutter Color?

Related Posts