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.
Creating a Firebase project
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.
Integrating Firebase with Android, iOS, and web
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 three platforms.
Android configuration
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 the android → app directory. Click on Next.
- Just follow the instructions provided, 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.
iOS configuration
Follow the steps below to complete the configuration on the iOS platform.
- Select the iOS icon on the dashboard.
- 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 the "Add to targets" box. Then click Finish. - You can skip steps 3 and 4, as they are automatically configured by the Flutter Firebase plugin that we will be adding soon. Click on Continue to console to go back to the dashboard.
Web configuration
Configure the Firebase project for the 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 into 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.
Getting started
Let’s take a look at the sample project that we will be building, and then start integrating Cloud Firestore with the Flutter app.
Project overview
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).
Enabling Cloud Firestore
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 set up 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.
Creating a Flutter project
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 the 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.
Adding Firebase to Flutter
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:
Install the packages from the 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:
LoginScreen
will be a StatefulWidget. Define a method inside it called _initializeFirebase()
that will initialize the firebaseApp.
Inside a FutureBuilder
call the _initializeFirebase()
method which will show the LoginForm
widget as the initialization is complete.
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.
Understanding Firebase structure
It's 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 a 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, you will first need to initialize the FirebaseFirestore
and define the main collection where all of the database information will be stored.
Now, we can start defining the CRUD methods in this class. We will start with the write operation.
Write data
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.
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.
Read data
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.
Update data
To update 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.
Delete data
To delete a note from the database, you can use its particular document ID and remove it using the delete()
method on the documentReferencer
object.
App in action
Congratulations 🥳, you have successfully defined the CRUD methods in Flutter to interact with the Cloud Firestore database.
A brief demo of the app is shown here:
Conclusion
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 this GitHub repository:
Originally published on Codemagic Blog.
Check out my other articles
If you want to support me and want me to continue writing Flutter articles and building some interesting Flutter projects, please contribute to my Patreon page below:
You can follow me on Twitter and find some of my projects on GitHub. Also, don’t forget to checkout my Website. Thank you for reading, if you enjoyed the article make sure to show me some love by hitting that clap (👏) button!
No comments:
Post a Comment