How to use Firebase realtime database with Flutter
Note: This post was originally published on February 2020 and has been completely revamped and updated for accuracy and comprehensiveness.
You started learning flutter and now you need a backend, you read about Firebase but didn’t really understand how to use it.
Well in this article I will explain how to integrate Firebase with Flutter, save and retrieve data from the Realtime database.
1st Note: Flutter is a hybrid framework for mobile applications, but for this article I’m only going to use it on Android device. Also I’m not going to go in depth about Flutter, the article is mostly about using Firebase realtime database in Flutter.
2nd Note: You can find the source code for all the Firebase/Flutter tutorials in the following repository: Firebase-Flutter-tutorials. Support me by starring the repository and following me on Github for more awesome content! Let’s get started 😁
Integrating Firebase in Flutter
So first, you need to have Flutter already installed in your operating system. I’m not going to go into that, but you can check here on how to install Flutter. Now open Visual studio code, and execute the following command:
flutter create firebase_with_flutter
This command will create a new project with the name firebase_with_flutter. Then to go to the directory of the project, execute the following:
cd firebase_with_flutter
code .
Now, if you execute flutter run
you will see a new application created on your device. Now in the next step, we start integrating Firebase into the project. So, first open the Firebase console and create a new project, after doing that you can click on the Android icon and start adding information related to the project. Now, you need to get the package name which you can find under the following path android\app\src\main\AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.firebase_with_flutter">
After following the steps, you can download the Firebase Android config file google-services.json and add it under android/app. You can check this answer to know exactly where to add the file. Now, you need to navigate to the android/build.gradle and add the google maven repository and the google-services classpath:
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
...
// Add this line
classpath 'com.google.gms:google-services:4.3.3'
}
}
allprojects {
...
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
...
}
}
Then inside your app android\app\build.gradle, add the following:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.gms.google-services' //this line
Now you can successfully use Firebase Realtime database in your project!
Save Data to Firebase
To be able to call the Firebase SDK, you can use the following plugins. Therefore inside pubspec.yaml
add the following:
dependencies:
firebase_core: ^1.0.3
firebase_database: ^6.1.2
and save by clicking CTRL + S, visual studio code will execute flutter packages get
and add the plugin to your project. Also you have to add the firebase_core
dependency to use any firebase products.
Since all firebase dependencies depend on firebase_core
, therefore you need to initialize Firebase to be able to call any method related to realtime database, firestore, authentication and so on. For example:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Here you initialize Firebase inside the main()
method, also please don’t forget to use async/await
since initializeApp()
returns a Future
. You can find different approaches to initalize Firebase here.
The WidgetsFlutterBinding.ensureInitialized();
will return an instance of WidgetsBinding()
, which is used to interact with the Flutter engine. The Flutter engine will have the platform channels which are used to asynchronously call native code and since Firebase.initializeApp()
has to call native therefore we ensure that WidgetsBinding()
is initialized. You can find a detailed explanation here.
Note: The pubspec.yaml is where you add all your dependencies that you are going to use in your project, it is similar to the build.gradle
file when creating a native android project.
⚠️ ⚠️Important Note⚠️ ⚠️: This tutorial is written using null safety, therefore when you create a project execute dart migrate --apply-changes
to migrate to null safety. In the above firebase versions, the firebase_core
supports null safety while the firebase_database
still doesn’t, so also when you want to run the application you need to do flutter run --no-sound-null-safety
or if you are using android studio then check this link.
To save data to the realtime database, first we need to get an instance of the database and then we can use the set
method to save the data:
So first, we use the StatefulWidget
since it is a widget that has a mutable state. Then we use the method createState()
that will return _MyHomePageState
. Now in this class you can add your logic and create a form. So first get an instance of Firebase by using FirebaseDatabase.instance
. Then create an instance of TextEditingController
that will be assigned to the property controller inside the TextField
widget.
The TextEditingController
will be used to retrieve the text written inside the TextField
. Then, you need to call the method reference()
that will return a DatabaseReference
. After that, create a ElevatedButton
and use the onPressed
property that will take a callback which will be called when the button is tapped or otherwise activated. Inside the callback, you can use the following code ref.child(name).set(myController.text)
, this will create an attribute in the database with the value of the TextField
.
Retrieving Data From Firebase
Now to retrieve data, you can use the following code:
We can create a new ElevatedButton
and inside the onPressed
callback, we can use the once()
method to retrieve the data once. Since once()
returns a Future<DataSnapshot>
then it is asynchronous and you can use the method then()
which registers a callback to be called when this future completes.
Since the data is of type DataSnapshot
, then you can use the property value to retrieve the content of this datasnapshot
.
I hope you enjoyed this Flutter article, in the next article I will go more in depth about retrieving and saving different Firebase database structure and will use queries to retrieve data.
Originally published at https://petercoding.com on February 6, 2020.