Flutter Recipes 2 — Firebase Firestore Recipes
I have built quite a few apps with Flutter and Firebase. And, for most of those projects I used Firestore as the database. So, I had to perform all sorts of query, pagination, mapping Firestore returned Maps to data models. So over that period of time, I have created a simplified, generalized helper class with various methods that help me work with Firestore database. That is what I am publishing here. Hope it will be useful for those using Firestore in their database.
General Class
This class has the most commonly used methods on firestore. It can get list of items from collection, single item, remove item, add item. It provides list and single item both as a future and stream. It also provides methods for easier query and simple paginations. It uses generic type so that, we can use it to convert firestore map to the required data model we want
Using it in Action
Below I will show how to use this class to get a list of Note
items from notes
collection.
Step 1
We create a notes item model for our data
class Note{
final String title;
final String id;
final String description;
final DateTime createdAt;
final String userId;Note({this.title, this.id, this.description, this.createdAt, this.userId});Note.fromDS(String id, Map<String,dynamic> data):
id=id,
title=data['title'],
description=data['description'],
userId=data['user_id'],
createdAt=data['created_at']?.toDate();Map<String,dynamic> toMap() => {
"title":title,
"description":description,
"created_at": createdAt,
"user_id": userId,
};
}
Step 2
We instantiate the generic class using the Note
model as our type. Pass the collection path as notes
and provide functions to convert from DocumentSnapshot
to note
and note
to Map
DatabaseService<Note> notesDb = DatabaseService<Note>("notes",fromDS: (id,data) => Note.fromDS(id,data), toMap:(note) => note.toMap() );
Step 3
Finally we can use notesDb
instance to work with notes
collection in our Firestore. For example to create item
Note note = Note(
title: "Hello Note",
description: "This is notes description",
);
notesDb.createItem(note); //this function will add our note item to the firestore database
You can see this in action in the following repository
Want to connect with me
Facebook: https://fb.me/lohanidamodar
GitHub: https://github.com/lohanidamodar
YouTube: https://youtube.com/c/reactbits
Twitter: https://twitter.com/LohaniDamodar
Linked In: https://www.linkedin.com/in/lohanidamodar/