Using Firebase Firestore in Flutter
Introduction
In this post, we shall discuss the cloud firestore. We will learn about the various curd operation with the firestore. If you want to store the data locally inside your app you can read my post on the moor library.
Link :
Moor in Flutter
MOOR is a library allowing us to work with the Flutter’s SQLite database fluently and in pure Dart…medium.com
Table of content
- cloud firestore vs realtime database
- Setting up the project.
- Adding required dependencies.
- Creating a collection on the cloud firestore.
- Uploading data.
- Fetching data.
- Deleting Data
- Updating Data
- Designing the UI.
Cloud firestore vs Realtime database
- It provides us more structural data.
- This database is scalable.
- East to fetch the data.
- Multi-region support.
- Range of pricing model.
- Data validation happens automatically.
Setting up the project
How to integrate firebase with flutter android or ios app ?
- Open firebase, click on get started which will take you to the Add Project screen.
- Enter the project name and complete the other essential steps. It will take you to your project screen, click on the android icon.
- Now the steps which are coming are very important so please do them very carefully. You have to enter the package name which is generally your application Id in your app-level build.gradle file. Add the other two optional fields if you wish to add them as well.
- Now download the google-services.json. Move the downloaded google-serivces.json file into your Android app module root directory. (NOTE: Please check the file that you have downloaded has a google-services.json name or not because if you download it more than one time the name of the file changes to google-services(2).json, so please remove (2) from the file name or rename it to google-services.json)
- You will see the following screen.
Here the first block contains the classpath that you have to add to your project level build.gradle file under the dependencies section. The second section contains a plugin and dependencies that you have to add to your project app-level build.gradle file. Please add these lines properly and carefully if you are adding them for the first time.
6. Now you should restart your application (NOTE: Please refer to full restart not hot reload). Wait for few seconds and your application will be successfully added with firebase. If you see the bellow screen on your firebase then you have successfully added firebase to your app…
Adding required dependencies
We will require the following dependencies
dependencies:
cloud_firestore:
Also, import the package to your file.
import 'package:cloud_firestore/cloud_firestore.dart';
Please add these line in your app/build.gradlemultiDexEnabled true
to your defaultConfig
section and also add implementation 'com.android.support:multidex:1.0.3'
to the dependencies
section.
Creating a collection on the cloud firestore
- Click on start collection and enter the Collection ID.
- Enter the field name with type and value.
Here I have created a collection of products that contain two documents and it has four fields i.e productName, productPrice, imageUrl, isFavourite. You can customize them according to your requirements.
Uploading Data
To upload the data on the firestore we need to create a firestore instance.
Future<void> uploadingData(String _productName, String _productPrice,
String _imageUrl, bool _isFavourite) async {
await Firestore.instance.collection("products").add({
'productName': _productName,
'productPrice': _productPrice,
'imageUrl': _imageUrl,
'isFavourite': _isFavourite,
});
}
Here I have declared an async function that takes two arguments as parameters.
collection() statement takes the collection name that we have initialized in our cloud Firestone.
.collection("students")
Fetching Data
We need a stream that will control the flow of data from the database to our app.
stream: Firestore.instance.collection("products").snapshots(),
collection() statement takes the name of a collection that we have created in the previous section.
To implement the stream we require a StreamBuilder.
StreamBuilder(
stream: Firestore.instance.collection("products").snapshots(),
builder: () {},
);
StreamBuilder builder takes the context and the snapshot.
StreamBuilder(
stream: Firestore.instance.collection("products").snapshots(),
builder: (context, snapshot) {},
);
builder: (context, snapshot) {
return !snapshot.hasData
? Text('PLease Wait')
: ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot products =
snapshot.data.documents[index];
return ProductItem(
name: products['name'],
imageUrl: products['imageURL'],
price: products['price'],
discription: products['description'],
);
},
);
},
products is a DocumentSnapshot, which we will use as an entity to access the various field.
DocumentSnapshot products = snapshot.data.documents[index];
snapshot.data.documents.length is the length of documents that we have created in our database.
itemCount: snapshot.data.documents.length,
We are returning a Text if the data is under the fetching process and if the data is loaded from the database then we build a ListView.builder which returns a ProductItem() widget.
Deleting Data
Deleting the data require a DocumentSnapshot to excess the documentID of the specific collection. It also requires the collection name.
Future<void> deleteProduct(DocumentSnapshot doc) async {
await Firestore.instance
.collection("products")
.document(doc.documentID)
.delete();
}
Editing Data
Editing the data require the id of the document and the name of the collection.
It also requires the updataData() statement which takes the fields that are needed to be updated.
In this particular case, I am updating the favorite feature of the app.
{"isFavourite": !_isFavourite}
Here every time the user press the favorite its value will be updated to its opposite value.
Future<void> editProduct(bool _isFavourite,String id) async {
await Firestore.instance
.collection("products")
.document(id)
.updateData({"isFavourite": !_isFavourite});
}
All Operation
operation.dart
https://gist.github.com/anmolseth06/ac4b329e2ce1f3eba8adda734c21b50b#file-operation-dart
Designing the UI
homePage.dart
https://gist.github.com/anmolseth06/b5a609b6b159fcad834ae86e88b8e2a3#file-homepage-dart
Product Widget
https://gist.github.com/anmolseth06/41ccc95ef240ac1f89508153b73c0e70#file-productitem-dart
Adding Product Screen
https://gist.github.com/anmolseth06/a601b9246e4474ec1b92bfa0b26e8176#file-addproduct-dart
Full Project
flutter-devs/firestore-Database-Demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com
Thanks for reading this article ❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
If we got something wrong? Let me know in the comments. we would love to improve.
Feel free to connect with us:
And read more articles from FlutterDevs.com
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, and Twitter for any flutter-related queries.
We welcome feedback and hope that you share what you’re working on using #Flutter. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!
Thank you for reading. 🌸