Open In App

Flutter - Realtime Database in Firebase

Last Updated : 09 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Firebase Setup
  2. Add Realtime Database to application
  3. 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’.

Firebase_console


Step 2: Give a name to our project and click ‘Continue’.

enter_project_name


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.

Realtime_Database


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

create_db
country
test_mode


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 :

add_link


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:

Add_data


Realtime Database:

added_data_in_db


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:

read_data_from_db


Realtime Database:

read_db


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.


Next Article

Similar Reads