Flutter Firebase Firestore Tutorial

Cloud Firestore is a service provided by Google Firebase development platform. it’s a non-SQL cloud database to store and synchronize data for client and server side development. It’s database which mobile, web, and server apps can access via native SDKs via IOS, Android, or web apps.

In other words, Firestore is a very effective tool to store app’s data in high flexibility and scalability.

In this article, we’ll go through Flutter Firebase Firestore tutorial. We’ll discuss how to use Firebase Firestore in flutter apps and learn how to implement Flutter Firebase Firestore CRUD functions.  We’ll go through practical examples that shows you how to create collections and documents, how to secure your data, and how to add, update, delete and retrieve data from cloud Firestore.

So, without further ado, let’s start our Flutter Firebase Firestore tutorial!!

Table of Contents

What is Firebase Firestore?

Firebase Firestore has several capabilities including scalability, flexibility, offline synchronization, and real-time updates.

Firebase Firestore provides flexible, hierarchical data structures which store data in documents that are organized in collections. Each document can contain several fields as well as sub-collections which in turn can have more documents.  Documents can store fields in various data types such as string, number, date, array, boolean, map, etc. The ability to create collections and sub-collections makes Firestore scalable and flexible in use.

Firebase Firestore collections
Firestore collections and sub-collections

In addition, Firestore caches the data your app’s actively using which mean the app can read, write, listen, and query data even when the device’s offline. Once the device is back online, Firebase synchronizes the changes back to the cloud.

Now, Firestore querying is very flexible as it allows you to create query to retrieve data at document level instead of retrieving the whole collection. Moreover, it provides real-time listeners which help you keep the data in your app up to date without having to retrieve the whole database when a change or an update in the data occurs

Finally, Firestore provides you the ability to secure your data using Firebase Authentication and cloud Firestore security rules. This helps you to prevent or limit users from editing the app’s data to protect and secure the app.

Firestore Setup

First of all, you’ll need to create a new Firebase project using Firebase console and set it up for your application’s environment.

After you  successfully create the Firebase project, you’ll need to enable Cloud Firestore. To do that, navigate to your Firebase console and open your project. From your project’s dashboard, select Firestore dashboard from the left menu.

Firestore setup

Then, click on create database and select test mode

create firestore database
Create Firestore database
Firestore security mode
Firestore security mode

Next you’ll need to select your Firestore location where you’ll data you’ll be stored. Take note that you can’t change your data location after you set it up. I will be keeping the default location as my data location.

Firestore location
Firestore Data location

And that’s it, Firestore is now  successfully enabled. Next, we’ll be looking into how to create collections manually and using code

Create Firestore Collection

Collections in Firestore are the containers that organize documents which you can consider as tables in an SQL-based database. Inside collections, you can store data inside documents which you can consider as row. Each document has a unique ID and a set of key-value pairs (field and value) where you can store your data. You can specify the data type for each field in the document.

In the Firestore dashboard, inside the data section, you can see an option to start a collection. Once you click on start a collection, you can specify the collection ID (table name).

create firestore collection
Create firestore collection

Let’s create a collection with an ID “Users”.

create firestore collection ID
Create firestore collection ID

Then, we need to define the first document’s ID and fields. You can set an automatic document ID to avoid replication. Let’s create the following document:

  • ID: auto-ID
  • name (string): “Dan”
  • email (string): “example@gmail.com”
  • gender (string): “Female”
  • age (number): 25
Create firestore document
Create firestore document

and there you go, you’ve successfully created the first collection within your Firebase Firestore.

Initialize Firebase project in Flutter app

First thing to remember, to be able to work with any Firebase service no matter if it’s authentication, firestore, or any other service, you need to initialize the Firebase project within your Flutter app. For the purpose of doing so, you need to use the firebase_core plugin which is a part of FlutterFire package.

To do so, add the following dependency in the pubspec.yaml file within your Flutter project then click on pub get

firebase_core: ^1.20.0

Now, let’s initialize the Firebase project in the main.dart file. First, import the following package

import 'package:firebase_core/firebase_core.dart';
Then, in the main() function, add the following code

Future<void>  main() async {
  await Firebase.initializeApp();
  runApp(const MyApp());

Set up Firestore in Flutter project

Beside the need to use firebase_core plugin, you need to use the cloud_firestore plugin to enable using cloud Firestore functions. Like you did in the previous step, add the following dependency in the pubspec.yaml file then again click on pub get:

cloud_firestore: ^3.4.0

After that, import the following library in the dart file where you want to implement Firebase Firestore functions:

import 'package:cloud_firestore/cloud_firestore.dart';

After following all the steps, you’re good to start using cloud Firestore functions within your Flutter app so let’s start playing around with Firestore features!

Add data

You can add a document to the Firebase collection using the add method on a collectionReference. The add method creates a new document with a unique auto-generated Document ID.

First, let’s create an instance of Firestore by calling the instance getter on FirebaseFirestoreabove the build() method. This allows you to interact with Firestore using the default  Firebase app.

FirebaseFirestore firestore = FirebaseFirestore.instance;

Then, create a reference to the collection we previously created

CollectionReference users = FirebaseFirestore.instance.collection('Users');

Later, create a function addUser() to implement data insertion to Firestore collection

Future<void> addUser() {
      'name': 'Sam',
      'email': 'same@gmail.com',
      'gendger' : 'Male',
      'age': 20
    ).then((value) => print('User Added'))
        .catchError((error) => print('Failed to add user: $error'));

Now, you can call the function when a button is pressed

Read Data

Cloud Firestore gives you the ability to read the value of a collection or a document. You can read data from Firestore collections using the get method from the FirebaseFirestore instance.

In this tutorial, we’ll see an example to retrieve all documents from the Firebase collection. Firestore provides multiple methods to retrieve data based on various queries without having to specify the document ID. This will be covered in a separate tutorial that will only focus on retrieving data from Firestore collections.

let’s create the function getData() that will retrieve the users details in the firestore collection

Future<dynamic> getData() async {
      .then((QuerySnapshot querySnapshot) {
    querySnapshot.docs.forEach((doc) {

You can call this function inside onPressed() method and check if the results are printed in the terminal

firestore read data
Read data from collection

Update data

You can update the data of a document within a collection using the update method. Take note that you need to specify your own doc ID which you wish to update

void updateUser() {
  users.doc('U7CwuynRRSENTmsYawzh') // <-- Doc ID where data should be updated.
      'age': 30
  ).then((value) => print('User updated successfully'))
      .catchError((error) => print('Failed to update user: $error'));

Removing documents

You can delete a document from Firestore collections using the delete function on a DocumentReference.

Future<void> deleteUser() {
  return users
      .then((value) => print("User Deleted"))
      .catchError((error) => print("Failed to delete user: $error"));

If you want to delete a specific field within a document, then you need to use the delete method with FieldValue class

Future<void> deleteField() {
  return users
      .update({'age': FieldValue.delete()})
      .then((value) => print("User's Property Deleted"))
      .catchError((error) => print("Failed to delete user's property: $error"));

Secure Data

You can secure the data stored in Firestore using the Firebase authentication and cloud Firestore security rules if you’re using web, Android, or IOS apps.

From the Firestore dashboard, navigate to rules section where you can edit the read and write permissions for your data.

Deny read/write to all users

This prevents all users from accessing and manipulating your data under any condition.

Firestore security rules
Firestore security rules – Locked mode

Limit access to authenticated users

This allows users who are signed-in to read and data in your application

firestore security rules
Firestore security rules – Auth required


Congrats! you’ve completed the Flutter Firebase Firestore CRUD Tutorial!

Using Firebase services is truly effective not to mention how easy it is to catch and implement. We’ve learned how to set up Firestore in Flutter app, how to create collection, add data, update data, delete data, and how to read data. In Future posts, I will be covering querying that enables you to retrieve data based on specific requirements.

If you wish to learn more about Firebase, I have a whole category of Firebase that’s ripe for you to explore. You can learn about Firebase Email Authentication, mobile authentication, and Facebook authentication.

Also, don’t forget to like and share my Facebook page, share the post with those who care to learn, and subscribe to my blog to be one of the firsts to know about my newest posts!

Thank you and happy coding!

Oh hi there!
It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

Let's Do This!

2 thoughts on “Flutter Firebase Firestore Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top