Cloud Firestore provides you an easily manageable pre-configured NoSQL database. It helps in storing & syncing data for both client and server-side development; it also supports automatic caching of data for using it even offline. Google Cloud is the driving platform behind Cloud Firestore that can be scaled easily.
In this article, you will learn to integrate Cloud Firestore with Flutter, and perform CRUD (create, read, update and delete) operations.
So, let’s get started.
You will need to create a new Firebase project in order to integrate it with your application.
Navigate to the Firebase console and click Add project.
Enter a project name and click Continue.
You’ll be asked whether you want to enable Google Analytics for the project. We won’t need analytics since this is just a sample project, just click Create project.
If you do want to enable Google Analytics, you’ll be prompted on the next screen to select a Google Analytics account:
Wait for the project to be created, and you’ll be navigated to the project’s Firebase dashboard.
Though we’re using Flutter, which is a cross-platform framework, we still need to integrate the Firebase project separately for each platform.
Flutter 2.0 has support for Android, iOS and web in its stable channel, so we’ll configure Firebase for all the three platforms.
Let’s start by configuring for the Android platform.
-
Select the Android icon from the Firebase dashboard.
-
Enter the Android package name, an app nickname and the SHA-1. Click on Register app.
-
Download the
google-services.json
file and place it in android → app directory. Click on Next. -
Just follow the step and add the required code snippets to your project. Click on Next.
You have successfully configured Firebase for Android. On the final step, click on Continue to console to go back to the dashboard.
Follow the steps below to complete the configuration on iOS platform.
-
Select the iOS icon on the dashboard.
-
Enter your iOS bundle ID and an app nickname. Click on Register app.
-
Download the
GoogleService-Info.plist
file. Click on Next. -
Now, open the
ios
folder using Xcode, drag & drop the file that you downloaded into the Runner subfolder. When a dialog box appears, make sure that Runner is selected in “Add to targets” box. Then click Finish. -
You can skip the steps 3 & 4 as they are automatically configure by the Flutter Firebase plugin that we will be adding soon. Click on Continue to console to go back to the dashboard.
Configure the Firebase project for web by following the steps given below.
-
Select the Web icon on the dashboard.
-
Enter the App nickname and click on Register app.
-
Now, add the code snippets for integrating the Firebase SDK to the web app.
Then, click on Continue to console to navigate back to the dashboard.
Finally, you have completed the Firebase configuration for all the three platforms.
Let’s take a look at the sample project that we will be building, and then start integrating Cloud Firestore with the Flutter app.
We will be building a simple notes management app where you can see the list of saved notes, save new notes, and also update & delete them.
This sample app will consist of four screens; the first one will be a very simple login screen for authenticating a user. But as the main focus of this article is the database, we won’t go and set up a full-fledged authentication logic. The login screen will simply accept a unique identifier which can be later used to customize and store data privately for each user.
The other three screens will be a DashboardScreen (displaying the list of notes), AddScreen (for adding a new note item), and EditScreen (for editing an already saved note item).
You can enable the Firestore database by selecting Firestore from the left menu and then clicking on Create database.
Now, you will be prompted to select a type of security rule. Here, we will choose test mode (that is, the database is open to all and it doesn’t check for any kind of authentication) because we will not setup any kind of strict authentication for this sample app. Click on Next.
If you are working on a production app, make sure you define an appropriate security rule. You can learn more here.
Then, you have to select a Cloud Firestore location and click on Enable.
You will be taken to an empty Firestore database structure.
We will start adding data to the database using the Flutter app.
You can create a new Flutter project using the following command:
flutter create flutterfire_samples
Then open the project using your favorite code editor. For opening with VS Code you can use:
code flutterfire_samples
Flutter 2.0 has support for null safety in stable channel, but in order to use it inside the app you have to run a command for migrating the project to null safety.
Before running the migration command, check if all your current project dependencies support null safety by using:
dart pub outdated --mode=null-safety
Then, run the following command to migrate:
dart migrate
You can follow the migration guide here.
We will be using the following plugins in this project:
- firebase_core: Required for initializing Firebase and using any other Firebase plugins.
- cloud_firestore: Required for interacting with the Firestore database.
The latest version of both these plugins support null safety.
Add these to your pubspec.yaml
file:
https://gist.github.com/f5dd84069c9fe1ec0c05a1764b2d061a
Install the packages from command line using:
flutter pub get
Go to your main.dart
file present in the lib folder of the root directory. Replace the contents with the following:
https://gist.github.com/433335ce673af8dd748c6187fc6db1c7
LoginScreen
will be a StatefulWidget. Define method inside it called _initializeFirebase()
that will initialize the firebaseApp.
https://gist.github.com/a0d7bc500f6305eb8a0463e7dece0271
Inside a FutureBuilder
call the _initializeFirebase()
method which will show the LoginForm
widget as the initialization is complete.
https://gist.github.com/a08379a61bb6f2b9050f95b18f7b6a3f
Before moving on further with the UI, let’s take a look at how the Firestore database is structured, and then define methods for performing the CRUD operations.
Its important to understand how data is structured in the Firestore database before we start defining our CRUD methods.
Cloud Firestore mainly consists of collections, documents and fields (key-value pairs). Collections can contain number of documents, which in turn can consist of sub-collections and key-value pairs.
References are used for pointing to a particular location in the database, that information can be used for storing, retrieving, updating, and deleting data from the database.
You can learn more about the Cloud Firestore data model here.
Our database structure will be like this:
Let’s start defining the CRUD operations inside our Flutter app’s Dart code. Create a new class Database
inside a file called database.dart
.
Here, first initialize the FirebaseFirestore
and define the main collection where all of the database information will be stored.
https://gist.github.com/04400d17ddfac869bc217d6fe473935b
Now, we can start defining the CRUD methods in this class. We will start with the write operation.
The write operation will be used for adding a new note item to the Firestore. Define it inside a method called addItem()
by passing a title and description of the note.
https://gist.github.com/ceeec3d69c4d28c610a46ef8dd045afe
We use the set()
method on the documentReferencer
to write a new data to the Firestore, and we have passed the data as a map.
We can read data from Firestore in two ways, as a Future
or as a Stream
. You can use Future
if you want to read the data for a single time. But in our case we need the latest data available in the database, so we will use Stream
as it will automatically synchronize data whenever it gets modified on the database.
https://gist.github.com/2ff7f502aca78abddbafcd14fbedd887
For updating data of the database, you can use the update()
method on the documentReferencer
object by passing the new data as a map. To update a particular document of the database, you will need to use its unique document ID.
https://gist.github.com/7b540ff7cf795bf25426ebee2fe044da
For deleting a note from the database, you can use its particular document ID and remove it using the delete()
method on the documentReferencer
object.
https://gist.github.com/e793430349828b553f46aae18d5f480d
Congratulations 🥳, you have successfully defined the CRUD methods in Flutter to interact with the Cloud Firestore database.
A brief demo of the app is as follows:
Cloud Firestore also provides a number of filters that can be used while querying the database in order to sort the responses, search for responses having a particular format, etc. You can learn more about it here.
FlutterFire handles the official documentation of the Firebase plugins for Flutter, you can find them here.
You can get the entire code of this app from the GitHub repository.