Adding Dart Objects to Firestore in Flutter
I had previously written an article on How to Load Data from Firestore into a ListView.
Add To Firestore with Automatic Id
In this article, we’ll learn How to add Data into a Firestore Collection without Using the Firebase Console UI.
It is quite simple. There is a function to add a document to a Collection in the Firestore Library. We can pass a Map to it and we are done.
Here’s an example.
FirebaseFirestore.instance.collection("collection-name").add({
"title":"This is the value for Title",
"content":"This is the Content"
});
But as told in my Latest post on Firestore listview, we can convert Firestore data into Dart Objects and Vice-versa.
Convert Dart Object to Map
For that, let’s create a Model class Like the previous Post.
class NoteModel{
String title;
String content;
NoteModel({
required this.title,
required this.content,
});
}
Next, we have to create a Function that Will convert this Object into a Map.
Map<String,dynamic> toMap(){
return {
"title":title,
"content":content,
};
}
Put the above Function Inside our Model Class and It’ll convert our Dart Object into a Map.
Adding to Firestore
With the second method, we can add Data to Firestore simply.
First, create An Instance of our Notes Class.
NoteModel noteToAdd = NoteModel(
title:"This is an Awesome Title",
content:"This is the Content of the Note",
);
Next, we can simply add the above note to Firestore.
NoteModel noteToAdd = NoteModel(
title:"This is an Awesome Title",
content:"This is the Content of the Note",
);
FirebaseFirestore.instance.collection("Notes").add(noteToAdd.toMap());
Add to Firestore With Custom Id
All the above methods will create an Automatic document Id for the document we add. But If we want to provide a custom Id for a document, we can do it easily.
NoteModel noteToAdd = NoteModel(
title:"This is an Awesome Title",
content:"This is the Content of the Note",
);
FirebaseFirestore.collection("notes").
doc("your-desired-doc-id").
set(noteModel.toMap());
The above code will create a document with the Id we provided.
Please Note when we use set
, if there exists a document with the Same Id, It’ll be overwritten by the latest One.
Wrap
You can find more articles related to Firebase Here
Hope you found something useful here.
I’m always open to suggestions!
Let me know your suggestions and opinions on Twitter DM or drop a mail a [email protected].
If you’re feeling too generous, you can support me through Buy Me a Coffee.
Finally, if you found this helpful, please share this within your reach so that more people can benefit from this. And Follow me on Twitter for getting more posts like these 😉.