Skip to content
Related Articles

Related Articles

Flutter – Read and Write Data on Firebase
  • Difficulty Level : Medium
  • Last Updated : 10 Nov, 2020

Firebase helps developers to manage their mobile app 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. We will be using flutter for this. To do this job we need to follow the 3-step procedure:

  1. Adding firebase to our app
  2. Firebase Setup 
  3. Implement using Code

Adding firebase to our app

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: After creating your project on the left-hand side you will see these options

firebase menu



Step2: 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

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: Press Start collection

Step 2: Enter a name for collection id and select auto id for its document



collection idcollection idcollection id

Step 3: Press Add Field and add Field and Value as key-value pair

key-value pair

Step 4: Finally this is how your final screen will look

final screen

Implementation

Step 1: 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.

Step 2: In the terminal execute the following line.

flutter pub get

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 3: 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',
      home: AddData(),
    );
  }
}
  
class AddData extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: Text("geeksforgeeks"),
      ),
      body:Center(
        child: FloatingActionButton(
          backgroundColor: Colors.green,
          child: Icon(Icons.add),
          onPressed: () {
            FirebaseFirestore.instance
                .collection('data')
                .add({'text': 'data added through app'});
          },
        ),
      ),
    );
  }
}

Output :

Write Data

Explanation: 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 4: 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',
      home: AddData(),
    );
  }
}
  
class AddData extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        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:

 Read Data

Explanation: 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.

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
My Personal Notes arrow_drop_up
Recommended Articles
Page :