Firebase Realtime Database — Flutter💙💛

Abhishek Doshi
Google Developer Experts
5 min readMay 7, 2022

We will always need the use of a Database in our application. There are a lot of service providers who provide database usage. Firebase is one of them and it provides us Realtime Database.

The Firebase Realtime Database is a cloud-hosted NoSQL database that lets you store and sync data between your users in real-time in JSON format.

To start with Realtime Database, we have the following steps:

  • Enable Realtime Database from your Firebase Console
  • Write the backend code that will handle read and write for Realtime Database
  • Call functions from your UI to read and write data.

So, let’s get started!

Step 1: Enable Realtime Database from your Firebase Console

Go to your Firebase Console and from the right panel, go to Realtime Database. You will see a welcome screen with a button to Create Database .

Once you click on that, you will get a popup to select the region and whether you want to create the database in Test or Locked Mode. You can select based on your requirements.

Once the database is created, you will be landed on the database page.

We are actually continuing the app that we created in the Firebase Authentication and Firebase Firestore article. Feel free to check that out, it’s a simple login/register app where we are asking for some user details. So………… time for some action!

Step 2: Backend Code

So the next step is to create our heroic backend files that will handle the read-write for the real-time database. Before we start with the real-time database, we will have to create a method to get the current user-id in our auth package.

String getCurrentUserId() {
return _firebaseAuth.currentUser?.uid ?? '';
}

Before we start with our backend code, let’s see how the database stores the data. As we know, Firestore Database stores data in Collection-Document format, Realtime Database is a bit different. It stores the data in JSON format making it quite easy when we have to deal with lots of data as JSON is the most preferred format for large amounts of data. Hence, when we want to send data from our app, we will have to send it in Map data structure with String as the datatype of the key and the datatype of value can be dynamic. This is the reason we will have to use userID as the key instead of email because the email would contain special characters and nowhere in the whole world we have seen special characters or email as the key of JSON🤯!

So, let’s create a separate package for realtime database or simply create a file for storing the code (depending on your convenience, however, the package approach is good for making your app scalable). You will have to add firebase_database package in your pubspec.yaml file.

In the above code, for the write method, we are taking the userId and data from the user (from the parent function where this function will be called). Then we create the instance of the Realtime Database (a.k.a FirebaseDatabase). Now, as you can see, during creating the instance, we have passed user/$userId to the ref method. So, if the database doesn’t contain a JSON entry with this userID, it will create one, and if it already exists, it will use that record. And then we simply use the set method available in the package.

For the read method, we first create the instance in the same way and then use the get method to get the record of the provided user. Now, if the data exists, we create a map out of the snapshot value (because the data is available as an Object) and then here we are just returning the name of the user.

Step 3: Call functions from UI

Once the database code is ready, it’s time to use these functions from our UI. So our plan is to call the write function when a new account is created and call the read function when the user logs in. Simple!

Hence, while creating the account, we use the following code snippet:

RealtimeDatabase.write(
userId: _authService.getCurrentUserId(),
data: {
'name': event.name,
'email': event.email,
},
);

As we have used bloc earlier, we simply fetch the name and event from the event class and get the userId from the function that we created in authService.

Now, for reading the data, we call the read function:

final _name =
await RealtimeDatabase.read(userId: _authService.getCurrentUserId());

Here we are just passing the userId from the authService

Let’s see how it looks in the database

So here you can see, we have users at the root of the tree and inside that, we have a user with user id and each user id has 2 fields, email and name.

In this article, we just saw how to read and write data into Realtime Database. However, there are many other methods which we can use to manipulate the data. Feel free to check them with the official documentation.

Simple isn’t it? I hope you learned something new from this article!

Hope you enjoyed this article!

Feel free to try it yourself by cloning the GitHub Repository!

Doubts? Feel free to drop a message @AbhishekDoshi26

Don’t stop, until you are breathing!💙
- Abhishek Doshi

--

--

Abhishek Doshi
Google Developer Experts

Google Developer Expert — Dart, Flutter & Firebase 💙💛