Flutter Firebase Realtime Database Tutorial

Haris Bin Nasir Avatar

·

·

How to use Firebase Realtime Database in Flutter?

In this article, we will be taking a look at how to work with Firebase Realtime Database In Flutter.

Firebase is a Backend As A Service (BAAS) provided by Google and it offers services such as Real-time database, Cloud Storage, Authentication, Hosting and, some other features, that we can integrate into our Flutter project. The real-time database is the topic of this session. Firebase also has synchronisation, which ensures that if data changes, all linked devices are notified.

Flutter is a software development kit (SDK) for creating cross-platform apps. With a single code base, developers may target key platforms including iOS, Android, Windows, and Linux. Google’s Firebase technology allows developers to create mobile and online applications.

Introduction: Firebase Realtime Database In Flutter?

To integrate Firebase into a Flutter application and store and retrieve data using Firebase’s Real-Time Database.

Requirements

This is an easy-to-follow lesson for beginners.

For you to follow along with this tutorial, you should have the following:

  1. Flutter SDK installed on your computer.
  2. IDE such as Android Studio or Visual Studio Code.
  3. Have a Firebase Account

More information on setting up Flutter’s development environment can be found here

Setting up the project

Create a new Flutter project in Android Studio.

Open the pubspec.yaml file and add the following Flutter dependencies.

Copied!
dev_dependencies: flutter_test: sdk: flutter firebase_database: ^4.4.0 firebase_core : ^0.5.3

Use the pub get command to retrieve appropriate dependencies.

After that, open your browser and go to the Firebase website. As indicated below, we must start a new Firebase project.

By tapping the Android symbol, you may add your Flutter application to Firebase.

As indicated in the figure below, type the name of your application’s package.

Your package name can be found in the app-level – build.gradle file. After you’ve completed this step, click register app.

Download the google-services.json file and paste it into the android/app folder.

Paste classpath 'com.google.gms:google-services:4.3.3' in the project level – build.gradle file.

Copied!
dependencies { classpath 'com.android.tools.build:gradle:3.5.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.google.gms:google-services:4.3.3' }

Navigate to the app-level – build.gradle file and add apply plugin: 'com.google.gms.google-services' as shown below.

Copied!
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" apply plugin: 'com.google.gms.google-services'

After the project is created successfully, navigate back to the Firebase console’s realtime database section, and create a new database.

In the rules section, ensure that you click on test mode rather than the locked mode. This allows us to read and write the data without authentication. Note that these rules should not be used in a production application since anyone can access the data.

Copied!
{ "rules": { ".read": "now < 1610053200000", // 2021-1-8 ".write": "now < 1610053200000", // 2021-1-8 } }

You can find more information about changing the rules above for a production application here.

We have successfully set up Firebase and the Flutter project. Let’s design the UI.

Building the UI

The app’s user interface will be straightforward. It will allow a user to type a word or sentence and then save it to the Firebase database by clicking a button.

Create a new file called home.dart. In this file, create a stateful class and name it HomePage. We’ll create a stateful widget and scaffold, as shown below.

Copied!
class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold(); // add scaffold here } }

We can then create the above UI in this file by pasting the following code in the body section of the Scaffold.

Copied!
Scaffold( appBar: AppBar(title: Text("Firebase Demo"),), body: Container( child: Column( children: <Widget>[ SizedBox(height: 250.0), Padding( padding: EdgeInsets.all(10.0), child: TextField(), ), SizedBox(height: 30.0), Center( child: RaisedButton( color: Colors.pinkAccent, child: Text("Save to Database"), onPressed: () { //call method flutter upload } ) ), ], ), ),);

Import the HomePage class in the main.dart file. Ensure that the HomePage is initialized, as shown below.

Copied!
import 'package:flutter/material.dart'; import 'home.dart'; void main(){ runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: HomePage(), ); } }

Ensure that you have the following imports at the top of the Home page.

Copied!
import 'package:flutter/material.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:firebase_core/firebase_core.dart';
  • package:flutter/material.dart – This import allows you to access Flutter’s built-in widgets and other functionalities.
  • package:firebase_database/firebase_database.dart – This import helps access the Firebase Realtime database features.
  • package:firebase_core/firebase_core.dart – This dependency enables you to connect to different Firebase products.

Storing data

We will initialize a Firebase databaseReference object and use it to store data.

Copied!
final databaseRef = FirebaseDatabase._instance_.reference(); //database reference object void addData(String data) { databaseRef.push().set({'name': data, 'comment': 'A good season'}); }

The addData function stores the user input along with a string ('comment': 'A good season'). Essentially, we can add any object to the database.

We’ll call the addData function when the RaisedButton is clicked.

Copied!
onPressed: () { addData(textcontroller.text); //call method flutter upload })),

We’ll access the user input using a textcontroller. This element allows us to listen for changes in a TextField.

We need to include the textcontroller in the HomePageState class.

Copied!
class _HomePageState extends State<HomePage> { final textcontroller = TextEditingController();

The textcontroller is the added to the TextField widget, as shown below.

Copied!
TextField(controller: textcontroller),

Please note that we need to use a FutureBuilder for async operations. This class allows the application to retrieve results once the network operation is completed.

This class also helps us initialize the Firebase app. You can learn more about FutureBuilder from here.

Copied!
class _HomePageState extends State<HomePage> { final Future<FirebaseApp> _future = Firebase.initializeApp();

_future is then added to the FutureBuilder in the Scaffold. This operation is illustrated below. As noted, FutureBuilder helps in awaiting long-running operations.

Copied!
return Scaffold( appBar: AppBar( title: Text("Firebase Demo"),), body: FutureBuilder( future: _future, builder: (context, snapshot) { if (snapshot.hasError) { return Text(snapshot.error.toString()); } else { return Container(

Retrieving data

For simplicity, we will retrieve and print out the data in the console. This is shown below.

Copied!
void printFirebase(){ databaseRef.once().then((DataSnapshot snapshot) { print('Data : ${snapshot.value}'); }); }

We’ll call the function above in the _HomePageState class’s build method.

Here is the complete code for the HomePage class.

Copied!
import 'package:flutter/material.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:firebase_core/firebase_core.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { final textcontroller = TextEditingController(); final databaseRef = FirebaseDatabase.instance.reference(); final Future<FirebaseApp> _future = Firebase.initializeApp(); void addData(String data) { databaseRef.push().set({'name': data, 'comment': 'A good season'}); } void printFirebase(){ databaseRef.once().then((DataSnapshot snapshot) { print('Data : ${snapshot.value}'); }); } @override Widget build(BuildContext context) { printFirebase(); return Scaffold( appBar: AppBar( title: Text("Firebase Demo"), ), body: FutureBuilder( future: _future, builder: (context, snapshot) { if (snapshot.hasError) { return Text(snapshot.error.toString()); } else { return Container( child: Column( children: <Widget>[ SizedBox(height: 250.0), Padding( padding: EdgeInsets.all(10.0), child: TextField( controller: textcontroller, ), ), SizedBox(height: 30.0), Center( child: RaisedButton( color: Colors.pinkAccent, child: Text("Save to Database"), onPressed: () { addData(textcontroller.text); //call method flutter upload } ) ), ], ), ); } } ), ); } }

Results

When we click on the Save to Database button. The user input is stored in the real-time database, as shown below.

The following items are also printed.

Conclusion

We’ve designed a basic Flutter app that can store and retrieve records from the Firebase Realtime Database. When you’re working on your own project, keep the following points in mind.

  • To use Firebase’s products, such as the real-time database, you must first register an account.
  • Before you can use the Firebase Realtime Database in your app, you must first create it.
  • When you need to wait for network requests or activities, use a FutureBuilder object.

As always, If you have found this article useful do not forget to share it and leave a comment if you have any questions. Happy Coding

Leave a Reply

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