Mastering Firebase Cloud Firestore in Your Flutter Application
Written on
Chapter 1: Introduction to Firebase Cloud Firestore
In this guide, we will explore the essential steps for integrating Firebase Cloud Firestore with your Flutter application. You will learn how to read and write data effectively.
Please note that this article has undergone updates. For the latest information, refer to the updated version!
Firebase Cloud Firestore is a scalable NoSQL cloud database designed for storing crucial data for your applications. It boasts a high degree of flexibility and can be secured through access rules. In the sections that follow, we will cover:
- Setting up the database
- Navigating the Firebase database editor
- Accessing the database from a Flutter application
- Implementing security rules for access control
For a comprehensive guide, consider purchasing my ebook that delves deeper into building Flutter apps with Firebase, available on Gumroad!
To utilize the code examples provided, you must create a Firebase project. If you haven’t done so yet, here’s a helpful article detailing the necessary steps.
Chapter 2: Creating a Firebase Project and Linking it to Flutter
In this section, I will guide you through the process of creating a Firebase project and linking it to your Flutter app.
Initial Setup
Begin by accessing the Firestore Database section in your Firebase dashboard.
Next, initiate the creation of a new database by selecting the "Create database" button.
The wizard will prompt you to choose between production and test mode. For now, we will select test mode, with the understanding that security configurations will be implemented later. Be cautious, as lacking security rules allows anyone to read, write, or delete data from your database.
You will then select a location, which impacts pricing and availability (further details can be found here). In this instance, there will be no costs incurred as the database operations stay within the free tier.
After completing this setup, you will see an empty database ready for use.
Next, we will learn how to add, edit, and delete data, as well as configure security measures.
Working with the Firebase Editor
The Cloud Firestore editor allows you to manage your data directly from the web interface. Click on "+ Start collection" to create a new collection, which can be thought of as a folder containing multiple documents. For this example, we will name our collection "cars."
You will then be prompted to add your first document, which can range from a simple key-value pair to complex nested JSON objects. Each document requires an ID, which can be auto-generated by Firebase (recommended for now). Click the "Auto-ID" button to create one.
In this example, I've included some fields and values to illustrate the editor's functionality. Moving forward, we will primarily manage our data through code.
Accessing the Database from a Flutter Application
The first step is to install the cloud_firestore package, allowing you to interface with your database. The following code snippets will demonstrate how to get, add, edit, and delete data using Cloud Firestore.
The workflow for these operations is quite similar. Utilize FirebaseFirestore.instance to access a collection identified by a string, apply orderBy or where clauses, and perform an asynchronous get. The docs property will yield a List<QueryDocumentSnapshot<Map<String, dynamic>>>, which can be converted into a JSON Map using the data() method. Subsequently, you can transform the Map into a Dart object.
- To add documents with auto-generated IDs, use the add() method on the desired collection. If the collection does not exist, it will be created automatically.
- If you want to assign a specific document ID, utilize the collection("someCollection").doc("myUniqueDocId").set(data) method.
Understanding set vs. update
Consider a Firebase document structured as follows:
{ "text": "Hello World", "number": 3 }
Using the update operation with { "text": "World Hello" } modifies only the text property, leaving number untouched. Conversely, the set operation with { "text": "World Hello" } changes the text property but also removes number. Exercise caution when using set()!
For a complete example of basic database operations, refer to the source code provided.
Here’s a brief video demonstrating the application. It shows data insertion, two retrieval operations with sorting and filtering, and finally, data deletion.
The first video titled "Using Firestore as a backend to your Flutter app" provides a comprehensive overview of how to effectively use Firestore in conjunction with Flutter applications.
Setting Up Security Rules
Security rules are crucial for ensuring that only authorized operations are performed on your data. While numerous options exist for configuring these rules, I will provide a brief introduction. For more detailed information, please consult the Firebase documentation.
Your current rule may resemble the following:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.time < timestamp.date(2022, 6, 22);}
}
}
The initial line specifies the service being used, as rules can also apply to Cloud Storage and the Realtime Database. The subsequent match statements determine which entities the rule applies to, allowing for the nesting of multiple match statements. The allow statement specifies the conditions under which access is granted.
Some common methods include:
- get — read single documents
- list — read queries
- create — write new documents
- update — modify existing documents
- delete — remove data
- read — encompasses get and list
- write — includes create and update
The rule above denies access to all documents in the database after June 22, 2022. Here are some common conditions you might employ:
allow read, write: if false; // no access
allow read, write: if request.auth != null; // access when authenticated
match /users/{userId} {
allow read, write: if request.auth != null
&& request.auth.uid == userId;
} // access only own documents
match ... {
allow read: if true; // read access for everyone
allow write: if request.auth != null; // write access when authenticated
}
For additional examples, refer to the aforementioned articles and the Firebase documentation.
Conclusion
Cloud Firestore serves as a straightforward cloud database solution for your application. With the examples and source code provided, you should be well on your way to getting started.
For the complete source code, visit my GitHub page:
GitHub - xeladu/flutter_firebase
This repository contains the companion code for the Flutter Firebase Compendium.
This article is part of the Flutter Firebase Compendium, which includes numerous tutorials and guides on utilizing Firebase with Flutter apps.
Get the most out of Firebase for Flutter developers with my ebooks.
The second video, "Flutter & Firebase App Tutorial #16 - Firestore Database Setup," walks you through the setup process for integrating Firestore into your Flutter application.