Flutter - Realtime Database in Firebase
Last Updated :
09 Apr, 2025
Firebase helps developers to build and run their apps successfully; its backend is developed by Google. Firebase is very easy to use for beginners; it provides many functionalities like Firebase Authentication, Cloud Firestore, Realtime Database, Firebase Storage, etc, which help to build and optimize the application. In this article, we will learn about how to use the Firebase Realtime Database to read and write data in Flutter. This process includes three steps:
- Firebase Setup
- Add Realtime Database to application
- Implementation to read and write
Firebase Setup
Step 1: Open Firebase-Google in our browser then click on ‘Go to console’ in the top rightmost corner of the page (Make sure that we must log in through our Google account in firebase) and then click on ‘Add project’.
Step 2: Give a name to our project and click ‘Continue’.
Step 3: After successfully creating the project, this screen will appear and there will be a lot of options on the left side of the page provided by firebase and then Select the Realtime Database option among these.
Step 4: Press the ‘Create Database’ button and then Select any location or keep it as it is and then click to ‘next’ and Select the test mode option which gives access to read and write data in the database and Press ‘enable’.
After that Firebase Realtime Database setup is done successfully.
Add Realtime Database to application
Copy the Database URL from Firebase Realtime Database in the green box shown below and replace the URL with DatabaseURL in writeData() and readData() function in Add Data and Read Data code :
Implementation
Step 1: Add HTTP package in the pubspec.yaml under dependencies in flutter project:
dependencies:
flutter:
sdk: flutter
http: ^1.3.0
Save the above file.
Note: Please make sure that while adding the above code, it must be the same level as flutter.
After saving the file, if any error occurs then check the spacing of code with flutter and also check that you have added the correct version of the HTTP package.
Step 2: Add Data.
Dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
// Entry point of the Flutter application
void main() {
runApp(MyApp());
}
// Main application widget
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
// State class for the MyApp widget
class _MyAppState extends State<MyApp> {
// Key to manage the form state
final _form = GlobalKey<FormState>();
// Variable to store the title entered by the user
String title = "";
// Function to send data to Firebase Realtime Database
void writeData() async {
// Save the form state to retrieve the input values
_form.currentState!.save();
// Firebase Realtime Database URL (replace with your database URL)
var url = "DatabaseURL" +"data.json";
// (Do not remove “data.json”, keep it as it is)
try {
// Send a POST request to the database with the title data
final response = await http.post(
Uri.parse(url),
body: json.encode({"title": title}),
);
} catch (error) {
// Handle any errors that occur during the request
throw error;
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'RealTime Database',
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text("GeeksforGeeks"),
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
body: Form(
key: _form, // Assign the form key
child: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
SizedBox(
height: 10, // Add spacing between widgets
),
TextFormField(
decoration: InputDecoration(
labelText: "Enter Title", // Input field label
border: OutlineInputBorder(), // Input field border
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.green.shade900,
),
),
),
onSaved: (value) {
// Save the input value to the title variable
title = value!;
},
),
SizedBox(
height: 10, // Add spacing between widgets
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
onPressed: writeData, // Call writeData on button press
child: Text(
"Submit", // Button text
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
)),
],
),
),
),
),
),
);
}
}
Note: Please replace the Database URL which we will get in the “Add Realtime Database to application” step with DatabaseURL in the writeData() function.
Output:
Realtime Database:
Explanation of the above Program:
In the above code, we have created a textformfield and submit button. TextformField to get title data from user and submit button to call a function which writes data in firebase i.e key-value pair of “title”- user input is pushed into a realtime database. If Button is pressed multiple times then Data is stored repeatedly.
Step 3: Read Data.
Dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
// Main application widget
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
// Fetch data from the database when the app initializes
readData();
}
bool isLoading = true; // Flag to indicate if data is still loading
List<String> list = []; // List to store the fetched data
// Function to fetch data from Firebase Realtime Database
Future<void> readData() async {
// Replace the URL with your Firebase Realtime Database URL
var url = "DatabaseURL" + "data.json"; // Keep "data.json" as it is
try {
// Send a GET request to the database
final response = await http.get(Uri.parse(url));
// Decode the JSON response
final extractedData = json.decode(response.body) as Map<String, dynamic>;
// If the response is null, return early
if (extractedData == null) {
return;
}
// Iterate through the data and add titles to the list
extractedData.forEach((blogId, blogData) {
list.add(blogData["title"]);
});
// Update the state to indicate data loading is complete
setState(() {
isLoading = false;
});
} catch (error) {
// Handle any errors that occur during the request
throw error;
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'RealTime Database',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.green,
),
home: Scaffold(
appBar: AppBar(
title: Text("GeeksforGeeks"),
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
body: isLoading
? CircularProgressIndicator() // Show a loading indicator while data is being fetched
: ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: list.length, // Number of items in the list
itemBuilder: (BuildContext context, int index) {
return Container(
height: 50, // Height of each list item
child: Center(
child: Text(
list[index], // Display the title from the list
style: TextStyle(
color: Colors.green.shade900), // Text style
),
),
);
},
),
),
);
}
}
Note: Please replace the Database URL which we will get in the “Add Realtime Database to application” step with DatabaseURL in readData() function.
Output:
Realtime Database:
Explanation: In the above code, we create CircularProgressIndicator which will rotate until we fetch data from the firebase database and when we get data, it will show the list of data which we are in firebase in listview builder widget with green colored text data.
Similar Reads
Flutter - Read and Write Data on Firebase
Firebase helps developers to manage their mobile apps easily. It is a service provided by Google. Firebase has various functionalities available to help developers manage and grow their mobile apps. In this article, we will learn how to write and read data into/from Firebase. Follow the 3-step proce
4 min read
Data Organization in Firebase Realtime Database
Firebase Realtime Database is a powerful tool that allows us to store and synchronize data in real-time across all clients. However, organizing data effectively in Firebase Realtime Database can be challenging for beginners. Proper data organization is important for efficient data retrieval, minimiz
7 min read
Remote Config in Flutter and Firebase
In Current app development, it is essential to offer smooth updates without asking users to download a new version from the Play Store to improve user experience. Remote Config in Flutter with the power of Firebase allows developers to update app content and features dynamically without releasing a
8 min read
Reading Data in Firebase
Firebase a comprehensive platform for building mobile and web applications, provides powerful tools for reading and managing data. Understanding how to read data from Firebase databases is essential for developers working with Firebase. In this article, we will explore the concepts, methods, and exa
3 min read
Firebase Realtime Database: Reading and Writing Data
Firebase Realtime Database, a cloud-hosted NoSQL database developed by Google, provides a robust solution for achieving seamless real-time data updates across connected clients. In this article, We will learn about the Firebase Realtime Database, How to Setting Up the Firebase Realtime Database, wri
7 min read
Writing Data in Firebase
Firebase which is an robust mobile and web application development platform by Google, offers developers two powerful databases for storing and synchronizing data: Realtime Database and Cloud Firestore. These databases cater to different needs, from real-time synchronization to structured querying a
4 min read
How to use Firestore Database in ReactJS ?
Firebase is a comprehensive backend solution offered by Google that simplifies the process of building, managing, and growing applications. When developing mobile or web apps, handling the database, hosting, and authentication can be challenging tasks. Firebase addresses these challenges by providin
9 min read
How to Delete Data from Firebase Realtime Database in Android?
In this article, we will see How to Delete added data inside our Firebase Realtime Database. So we will move towards the implementation of this deleting data in Android Firebase. Â What we are going to build in this article? Â We will be showing a simple AlertBox when the user long clicks on the ite
4 min read
Flutter - Store User Details Using Firebase
Firebase is a product of Google that helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the Firebase side which makes it easy to use its features more efficiently. It provides services
3 min read
Flutter - Store Data in Hive Local Database
Hive is a data storage system on our phone where we can store data in boxes. We can store an integer, string, list of strings, Boolean, double, models, integers, etc., in Hive. Now, let us discuss where we can implement these. The first way we can use this is to save the user information user is log
12 min read