Open In App

Flutter – Read and Write Data on Firebase

Last Updated : 10 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 procedure to create application to read-write data in Firebase:

  • Adding Firebase to our app
  • Firebase Setup 
  • Create a Table in Firebase
  • Implement using Code

Adding Firebase to Flutter Application

To interact with Firebase, we have to register our app to Firebase. Follow this link to complete the initial setup.

Firebase Setup

After completing the above setup, follow these steps:

Step 1: Initial Step

After creating your project on the left-hand side, you will see these options

firebase menu


Step 2: Creating Database in Firebase

Select the cloud Firestore and then select  create database and then select test mode and press next.

Firestore


Step 3:

Select any location or you can keep it as it is and press enable

location


Creating Table in FireStore

After creating Cloud Firestore you will see the empty database, now you have to just create a table and add data to it later we will add data from our app. Follow the below steps to create a collection(tables).

Step 1: Initializing the Collection/Table

Press Start Collection


Step 2: Creating a Table

Enter a name for collection id and select auto id for its document

collection idcollection idcollection id


Step 3: Add Field and Value to Table

Press Add Field and add Field and Value as key-value pair

key-value pair


Step 4: Table Created

Finally this is how your final screen will look

final screen


Implementation Read and Write in Flutter

Step 1: Adding Dependencies

In your flutter project open pubspec.yaml and under dependencies add the following packages:

dependencies:
flutter:
sdk: flutter
firebase_core: "^0.5.0"
cloud_firestore: ^0.14.1

Save the above file.

Note: While adding the above code ensure that the code added should on the same level as flutter.

In the terminal execute the following line.

flutter pub get

Note: Before executing the above lines of code check whether you are in the right directory or not. The above code gets all the packages. If any error occurs please check your spacing while adding packages and also check that you have added the correct version of those packages.


Step 2: Write Data

Dart
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root 
  // of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase',
      debugShowCheckedModeBanner: false,
      home: AddData(),
    );
  }
}

class AddData extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
        title: Text("geeksforgeeks"),
      ),
      body:Center(
        child: FloatingActionButton(
          backgroundColor: Colors.green,
          foregroundColor: Colors.white,
          child: Icon(Icons.add),
          onPressed: () {
            FirebaseFirestore.instance
                .collection('data')
                .add({'text': 'data added through app'});
          },
        ),
      ),
    );
  }
}

Output :

firebaseread

Explanation of the above Code:

In the above code, we have created a floating action button in the center of the screen. When we press that button the key-value pair which we defined is sent to firebase and stored in it. Data will get stored repeatedly if the button is pressed multiple times. 


Step 3 : Read Data

Dart
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase',
      debugShowCheckedModeBanner: false,
      home: AddData(),
    );
  }
}

class AddData extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
        title: Text("geeksforgeeks"),
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance.collection('data').snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

          return ListView(
            children: snapshot.data.docs.map((document) {
              return Container(
                child: Center(child: Text(document['text'])),
              );
            }).toList(),
          );
        },
      ),
    );
  }
}

Output:

firebaseretrive

Explanation of the above Program:

In the above code, we fetch data from firebase and store it as a snapshot of our data. To print that data on screen we build a List view that displays the data as text.



Next Article

Similar Reads