Peter
Peter Software Developer | Technical Writer | Actively helping users with their questions on Stack Overflow. Occasionally I post here and on other platforms.

Get Started with Firebase in Flutter

Get Started with Firebase in Flutter
Source Code Follow me on

You heard about a UI framework for creating mobile applications called Flutter, and started learning it but now you need a database and read about Firebase!

Well in this article I will explain how to integrate Firebase with Flutter, save and retrieve data from the Firebase realtime database.


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.

ionic http

Integrating Firebase in Flutter

This is the first article related to Firebase in Flutter, you can check the other articles in the below links:

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:

1
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:

1
2
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:

1
2
<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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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:

1
2
3
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:

1
2
3
4
5
6
dependencies:
  cupertino_icons: ^1.0.2
  firebase_core: ^1.8.0
  firebase_database: ^8.0.1
  flutter:
    sdk: flutter

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:

1
2
3
4
5
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.

:fire::warning:Important Note:fire::warning:: This tutorial is written using null safety, therefore when you create a project execute dart migrate --apply-changes to migrate to null safety.

To save data to the Firebase realtime database, first we need to get an instance of the database and then we can use the set method to save the data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class _MyHomePageState extends State<MyHomePage> {
  final fb = FirebaseDatabase.instance;
  final myController = TextEditingController();
  final name = "Name";

  @override
  Widget build(BuildContext context) {
    final ref = fb.reference();
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Container(
            child: Column(
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(name),
                SizedBox(width: 20),
                Expanded(child: TextField(controller: myController)),
              ],
            ),
          ElevatedButton(
              onPressed: () {
                ref.child(name).set(myController.text);
              },
              child: Text("Submit"),
            ),
          ],
        )));
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }
}

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 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.

firebase started

Retrieving Data From Firebase

Now to retrieve data, you can use the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var retrievedName;          

            ElevatedButton(
              onPressed: () {
                ref.child("Name").once().then((DataSnapshot data){
                  print(data.value);
                  print(data.key);
                  setState(() {
                    retrievedName = data.value;
                  });
                });
              },
              child: Text("Get"),
            ),
            Text(retrievedName ?? ""),

We can create a new ElevatedButton widget 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. You can also use the property key to retrieve the current location of this dataSnapshot, so in this case it will return the attribute Name.

I hope you enjoyed this Flutter/Firebase 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.

 

Become a Patron!