This is a simple Flutter project that demonstrate all the CRUD functionality:
- Create / insert from firestore
- Retrive / View from firestore
- Update / Edit from firestore
- Delete / Remove from firestore
This source code designed for absolute beginner in Firebase Firestore and it demonstrates the simplest way to the basic functionalities above.
To get started to this project you should do the following steps:
- Sign in/up to firebase
- Go to console
- Start a new project
- Create a Firestore database
- Create a "books"" collection
- Add a new record with a "title" and "author" fields
- Download and input google-service.json to the correct location
- Run flutter pub get
If you are new to flutter and firebase check the video bellow to get more information on how to connect your flutter app with firebase project.
Map<String, dynamic> newBook = new Map<String,dynamic>();
newBook["title"] = "title value";
newBook["author"] = "author value";
Firestore.instance
.collection("books")
.add(newBook)
.whenComplete((){
// You can add your desire action after the row is added
} );
Basic Update function
Map<String, dynamic> updateBook = new Map<String,dynamic>();
updateBook["title"] = "title value";
updateBook["author"] = "author value";
// Updae Firestore record information regular way
Firestore.instance
.collection("books")
.document(document.documentID)
.updateData(updateBook)
.whenComplete((){
// You can add your desire action after the row is updated
});
Or update using a transaction
Map<String, dynamic> updateBook = new Map<String,dynamic>();
updateBook["title"] = "title value";
updateBook["author"] = "author value";
Firestore.instance.runTransaction((transaction) async {
await transaction.update(document.reference, updateBook)
.then((error){
// You can add your desire action after the row is updated
});
});
},
Firestore.instance
.collection("books")
.document(document.documentID) // Replace the document.documentID with the row id that you need to delete
.delete()
.catchError((e){
print(e);
});
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('books').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting: return Center(child: CircularProgressIndicator(),);
default:
return new ListView(
padding: EdgeInsets.only(bottom: 80),
children: snapshot.data.documents.map((DocumentSnapshot document) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 3, horizontal: 10),
child: Card(
child: ListTile(
title: new Text("Title " + document['title']),
subtitle: new Text("Author " + document['author']),
),
),
);
}).toList(),
);
}
},
);
}