Flutter-Firestore CRUD
Cloud Firestore is an amazing service that can be used as a backend in websites or app and it serve data when client is offline and sync that data to server once client gets online
Here, I would like to present codes to perform CRUD in firestore using flutter aka dart programing.
- Set Data
It will create collection and document if not exists and here we are using Future because we are making network request here and as you probably know it may take some time.
Future addNote(String title, String description) async {DocumentReference docRef = Firestore.instance.collection(uid).document();await docRef.setData({"title": title,"description": description,"lastEdit": lastEdit,"docId": docRef.documentID});}
2. Read Data
Reading data from firestore is super easy.
var data;readNote() async {CollectionReference colRef = Firestore.instance.collection(uid);colRef.snapshots().listen((snapshots) {data = snapshots.documents;});}
We receive response as snapshot and we can deserialize it like below
var title = data[index]["title"];var description = data[index]["description"];var lastEdit = data[index]["lastEdit"];var docId = data[index]["docId"];
3. Delete Data
Future deleteNote(uid, docId) async {CollectionReference colRef = Firestore.instance.collection(uid);await colRef.document(docId).delete();}
4. Update Data
Future updateNote(uid, docId, String title, String description) async {CollectionReference colRef = Firestore.instance.collection(uid);await colRef.document(docId).updateData({"title": title, "description": description, "lastEdit": lastEdit});}
and that’s all in case of firestore-flutter