Get Started with Firebase in Flutter

Updated
6 min read
Source Code Follow me on

Peter Haddad

Software Developer | Technical Writer | Actively helping users with their questions on Stack Overflow.

firebase flutter

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.


info

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:

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

Now that you have configured the project in Firebase console. All you have to do is open the terminal and execute the following command:

dart pub global activate flutterfire_cli

This will download the flutterfire_cli which will take care of configuring Firebase in your project. In this case you don’t need to download individual google_service.json file since flutterfire_cli will add it and add the files for the other platforms automatically. So after downloading the flutterfire_cli, execute the following command:

flutterfire configure

Follow the steps, you will then be asked on which project you want to connect and then on which platform you want to configure Firebase. After configuration is done, you will have a file under the lib folder called firebase_options.dart, which will contain the apiKey and all of the information needed to configure Firebase. We would then use the property currentPlatform from the class DefaultFirebaseOptions in a later section.

Note: In case you recieved the error flutterfire command not found then you need to add it to the path by executing the following in macos export PATH="$PATH":"$HOME/.pub-cache/bin".

Note: In case flutterfire is not able to fetch your projects, then you might need to login to Firebase using the CLI. So execute the following two commands:

npm install -g firebase-tools
firebase login

Then flutterfire would be able to fetch your projects.

That’s it, now you have Firebase setup 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:
  cupertino_icons: ^1.0.8
  firebase_core: ^3.3.0
  firebase_database: ^11.0.4
  flutter:
    sdk: flutter
 
dev_dependencies:
  flutter_test:
    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:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(MyApp());
}

Here you initialize Firebase inside the main() method, also please don’t forget to use async/await since initializeApp(options: DefaultFirebaseOptions.currentPlatform) 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(options: DefaultFirebaseOptions.currentPlatform) 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.

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:

class _MyHomePageState extends State<MyHomePage> {
  final fb = FirebaseDatabase.instance;
  final myController = TextEditingController();
  final name = "Name";
 
  @override
  Widget build(BuildContext context) {
    final ref = fb.ref();
    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:

var retrievedName;          
 
  ElevatedButton(
    onPressed: () {
      ref.child("Name").once().then((DatabaseEvent data) {
        print(data.snapshot.key);
        print(data.snapshot.value);
        setState(() {
          retrievedName = data.snapshot.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<DatabaseEvent> 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 DatabaseEvent, then you can use the property snapshot which you would be of type DataSnapshot and that class would contain both the key and value properties to be able retrieve the content of this snapshot. You can also use the property key to retrieve the current location of this snapshot, 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.

Explore Categories

Browse articles by topic to find exactly what you're looking for