In the recent article, we gave you a complete guide on how to integrate firebase with your Android, iOS, and Web flutter apps. Before we move on, you should give it a look. If you know how to do that, let’s move forward to learn how to store data in the cloud firestore for flutter apps.
In mobile app development, storing and saving users’ data is the most important part of your app. You can save data in different ways using cloud firestore. You can either save the data locally, which means that you can’t share it with others, or save it permanently. So If you want to share your data, you need to save it in the cloud.
One of the easiest solutions to this problem is Google’s Cloud Firestore database. Cloud Firestore is a flexible and scalable NoSQL-style database. It is the best approach for small-sized projects to store and sync data for client and server-side development. Unlike traditional databases that require a lot of work to insert data, Firestore lets you save JSON blobs to collections. This method doesn’t limit you to structure your data and allows you to change it at any time.
Creating Firestore Database
After that, you’re done creating the project and integrating it with the flutter app, now it’s time to create the Firestore database. For this purpose, click on the Firestore database option appearing in the left navigation menu bar on the firebase homepage. As shown here:
The cloud firebase window will appear. Click on the “Create database” button. See here:
As you click on the create database, a new popup window will appear asking you to choose production mode or test mode. Now the question is which one to choose?
The production mode has increased security which requires a series of steps to consider. You won’t be able to handle the requests or the errors if you’re not ready for them. So we choose test mode which you can alternatively call debug mode. In this mode, you can make changes, remove errors, etc. We are moving on with test mode. As I said earlier, you can choose production mode if you’re ready for it. No enforcement. 😛
When you select a mode, the next step is to state the location where you want to create the database. There are different locations to choose from. By clicking on the Cloud Firestore location dropdown, you’ll be able to choose a multi-regional or regional location. You can choose the location according to your requirements or that is closest to your location and then click ‘enable’.
As you click enable, the Firebase will provision your Cloud Firestore database and you will be ready to use the database and perform what we are here for. The database console page is shown in the figure below:
Collections and Documents in NoSQL
A NoSQL database is made up of collections that contain documents in it. A document basically contains the fields that you plan to store, fields being the information or the parameters.
You can add collections using simple steps. Let me give you a quick go-through of it.
Click on “start collection” in the Cloud Firebase console. A new “start a collection” popup will appear. Enter a collection ID, which is a set of documents that contain data. Then click next. But It will require a document ID that denotes a particular set of data. And then you have to enter different fields like the name, age, or height of a person.
We are going to have a coding approach using the flutter app that we integrated with firebase.
Add, Update, Delete or Fetch Documents in Firestore Using Flutter App
In contrary to storing data in firestore through the console, you can also store data in firestore using the flutter app.
To accomplish this task, firstly, you need to create a model to store the data. But here, we are storing users’ data like name, age, etc.
Creating a model
To organize the data of users, we need to create a model from which we can access the data of an individual or everyone present in the model. So the code to create a model in the flutter app is given below.
class UserModel{
UserModel({
required this.name,
required this.phone,
required this.age,
});
String name;
String phone;
int age;
Map<String, dynamic> toJson() => <String, dynamic>{
'name': name,
'phone': phone,
'age': age,
};
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
name: json['name'] as String,
phone: json['phone'] as String,
age: json['age'] as int,
);
}
Add a Document
So you can add a document in firestore using the flutter app with the code given below.
Future<UserModel> insertFirestore(UserModel model) async {
try {
final document = await FirebaseFirestore.instance
.collection(collectionName)
.add(model.toJson());
model.id = document.id;
return model;
} catch (e) {
rethrow;
} }
Update the Document
You can update an existing document in firestore using the code as follows.
Future updateFirestore(UserModel model) async {
try {
await FirebaseFirestore.instance
.collection(collectionName)
.doc(model.id)
.update(model.toJson());
} catch (e) {
rethrow;
}
}
Delete a Document
But If you want to delete any document in firestore, you can use the code given below.
Future deleteFirestore(String documentId) async {
try {
await FirebaseFirestore.instance
.collection(collectionName)
.doc(documentId)
.delete();
} catch (e) {
rethrow;
} }
Fetch a Document
You can also fetch the data stored in a particular document in Firestore using the flutter app. Just use the code given below.
Future<UserModel> fetchOneFirestore(String id) async {
try {
return parseModel(await FirebaseFirestore.instance
.collection(collectionName)
.doc(id)
.get());
} catch (_) {
rethrow;
} }
Fetch all Documents
You can also fetch all the documents stored in Firestore.
Future<List<UserModel>> fetchAll() async {
try {
final _data =
await FirebaseFirestore.instance.collection(collectionName).get();
return _data.docs.map((document) => UserModel.fromJson(document.data())).toList();
} catch (e) {
rethrow;
} }
Final Words
In this article, we covered almost all about storing data in a cloud firestore using the Flutter app. So you can add the documents manually from the console as well. It was a short, but concise guide on how to store data in Firestore to let you know how easy it could be if you pay a little attention.
Got any suggestions or queries? Just leave a comment and let’s discuss your ideas.
Moreover, if you are looking for a flutter app development company to build scalable cross-platform flutter apps, then FlutterDesk is your right choice. Want to know why?
Having 5 years of demonstrative experience in mobile, web, and desktop apps, FlutterDesk has got all the expertise to overcome any of your complex problems. Hire a Flutter developer to turn your dreams into reality.