Flutter Firebase Realtime Database- Flutter Tutorial
Firebase Realtime Database on Flutter app is really super easy to integrate. You can perform all CRUD operations with just a single line of code. As I am very passionate about Flutter & Firebase, So I am writing this article that includes all CRUD on Realtime database.
Flutter Firebase Realtime Database integration is very simple. You can complete every firebase database CRUD operation with just one piece of code. Flutter with Firebase is now officially named FlutterFire. Firebase Database is a cloud-based database that stores data within a JSON structure. Note — Firebase real-time databases and Firebase Firestore are distinct things. Firebase Real-Time Database stores all information in a single large JSON file. however, firestore is an array made up of many JSON files known as collections. In this tutorial on firebase databases in Flutter, it is necessary to include the firebase_core as well as the firebase_database plugins to the Flutter project. You can download the source code from our website.
All devices connected with Firebase Realtime Database whether it is a mobile device or website automatically receive updates from Firebase with the newest data. You don’t need to call any external services to get data from the firebase realtime database in a flutter.
Flutter is a cross-platform development framework. So Flutter 2 now officially release the stable version of flutter web. If you want to build a responsive website using flutter then this article definitely helps you Flutter Web — How to build a responsive website. Same like flutter App, to read data from realtime database in flutter web, no need to add extra code. The same code base will be executed on the flutter web as well. All you need to do is just add two JS scripts on the index.html file inside the web folder.
To Watch Video — Flutter Firebase Database
Step by Step Process
- Create Firebase Realtime Database
- Add Flutter Plugin
- Configure Android & iOS folder
- Configure Web Folder
- Initialize FirebaseApp
- Perform CRUD Operation
Create Firebase Project
First, you need to create Firebase Project on Firebase console. Click on Add new project and provide a project name. The next step is to connect the android app and ios app with the firebase project. On the Firebase dashboard, You can see the android and ios icons. Click on the android icon to add the android package name and add the SHA key. Download the google-services.json file and put it inside the flutter project location “android–> app”. Open root level gradle file and add google service like below. Same steps you need to follow if you will try to Integrate Firebase Push Notification in Flutter App.
buildscript {
repositories {
google()
jcenter()
} dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath 'com.google.gms:google-services:4.3.10'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
Add Flutter Plugins
Add Firebase to your flutter app is easy. Open pubspec.yaml file and add firebase core and firebase database plugins. Firebase is now officially supported by flutter. To get data from realtime database firebase flutter core and firebase flutter database plugins are used. Firebase core and firebase database native dependencies are just wrapped with flutter and dart to make it compatible with the flutter project.
firebase_core: ^1.7.0
firebase_database: ^8.0.0
Configure Android & iOS folder
Flutter app doesn’t add internet permission in androidmanifest.xml file for android app. So go inside android folder and open the androidmanifest.xml file and add the below line just before starting of application tag.
<uses-permission android:name="android.permission.INTERNET"/>
Open iOS folder and open Podfile. There change the platform version number from 9.0 to 10.0.
platform :ios, '10.0'
Configure Web folder
Flutter 2.0 web is also supported by the Firebase database. Like gradle dependencies that we added in the android folder, Same way you need to add javascript files for the firebase database in the index.html file.
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-database.js"></script>
Initialize FirebaseApp
You can download the source code from our website. Now we are ready to write flutter code to retrieve data from the firebase realtime database and perform CRUD operations as needed. You should Keep remembering Whenever you use firebase in your flutter project the firebase app must initialize before the start of runApp(). Extent main() with async and initialize firebase app before runApp().
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_app_firebase_noti/realtime_db.dart';
Future<void> main() async{
WidgetsFlutterBinding.ensureInitialized();
// ensure initialisation
FirebaseApp firebaseApp = await Firebase.initializeApp();
runApp(MaterialApp(
home: realtime_db(),
) );
}
I have created a separate dart class name as “realtime_db“. First, create a simple UI for your Flutter app, So on button click, you can perform some actions. I am using the Column widget and textbutton widget to display the button on the app screen. For each CRUD operation, I am creating a separate function. Below is build() method code.
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text( countvalue.toString()+ " database - " + databasejson),
),
TextButton( onPressed: () {
_createDB();
}, child: Text(" create DB")),
TextButton(onPressed: () {
_realdb_once();
}, child: Text(" read value")),
TextButton(onPressed: () {
_readdb_onechild();
}, child: Text(" read once child")),
TextButton(onPressed: () {
_updatevalue();
}, child: Text(" update value")),
TextButton(onPressed: () {
_updatevalue_count();
}, child: Text(" update counter value by 1")),
// _updatevalue_count()
TextButton(onPressed: () {
_delete();
}, child: Text(" delete value")),
],
),
),
),
);
}
Here comes the important part. How to access the firebase database using dart code? To access the firebase database, the firebase database plugin having an object name as databasereference. Initialize the databasereference with the firebase instance.
late DatabaseReference _dbref;@override
void initState() {
// TODO: implement initState
super.initState();
_dbref = FirebaseDatabase.instance.reference();}
Create Firebase Database
You can simply create a single/multiple nodes in the database using the set() method. Create a child() with name and call set() to insert data into the database.
_createDB() {
_dbref.child("profile").set(" kamal profile");
_dbref.child("jobprofile").set({'website': "www.blueappsoftware.com", "website2": "www.dripcoding.com"});
}
Read data from Firebase Database
Firebase database can read at once() OR can read the specific child value by calling the child() name. Data is store in a JSON format as key-value pair. So if you want to read a specific child node value, you can use the child name(“key”) to get the value. This operation is Future<> type so use then() to read the value from the database.
_realdb_once() { _dbref.once().then((DataSnapshot dataSnapshot){
print(" read once - "+ dataSnapshot.value.toString() );
setState(() {
databasejson = dataSnapshot.value.toString();
});
});
}_readdb_onechild(){
_dbref.child("jobprofile").child("website2").once().then((DataSnapshot dataSnapshot){
print(" read once - "+ dataSnapshot.value.toString() );
setState(() {
databasejson = dataSnapshot.value.toString();
});
});
}
Remove data from Firebase Database
As like set() operation, You can remove any child node from the JSON tree. You can also remove the entire database at once. The remove() is used to remove the child from the firebase realtime database.
_delete(){
_dbref.child("profile").remove();
}
Update data onFirebase Database
Use update() to perform update operation on JSON child node.
_updatevalue(){
_dbref.child("jobprofile").update( { "website2": "www.dripcoding.com2"});
}
Run Flutter Project
Run the flutter project and test all the CRUD operations of the flutter firebase database. If you will face any issues, you can contact me.
Learn Complete Flutter App Development — https://www.dripcoding.com/best-flutter-online-course/
If you like the video, Please do Subscribe to our YouTube channel — https://www.youtube.com/channel/UC0tb4vuqPimSCWdnJailrTw?sub_confirmation=1
You can connect with us on Social Platform
Facebook — https://www.facebook.com/dripcoding
Telegram — t.me/dricoding
Instagram — https://www.instagram.com/the_kamal_bunkar/
Youtube — https://www.youtube.com/channel/UC0tb4vuqPimSCWdnJailrTw?sub_confirmation=1
Linkedin — https://www.linkedin.com/in/kamal-bunkar/
Pinterest — https://in.pinterest.com/kamalbunkar0229/_saved/
Facebook — https://www.facebook.com/kamal.bunkar/
You can also WhatsApp me at +91–9144040888 OR email me at kamal.bunkar@dripcoding.com , kamal.bunkar@blueappsoftware.com
Help & Support
If you will face any issue during firebase integration, Please leave your comment below or You can contact me on my social media channel. My Social media links are available above.
Feel Free to contact us.