How can I integrate Firestore Database with Flutter?

Hello Guys,

In one of my previous articles, I mentioned using Firebase real-time database with flutter. Cloud Fire store is a more advanced version of it from Firebase. I’ll walk you through how to use Cloud Fire store in Flutter step by step.

Cloud Firestore

Cloud Firestore is a NoSQL database similar to realtime databases, with the exception of the data storage structure. Data is stored in a JSON tree in a real-time database. We have a collection in Cloud Firestore. Documents, which include data, can be found in any number of collections. Cloud Firestore scales automatically, with a current capacity of roughly 1 million concurrent connections and 10,000 writes per second.

Creating a New Firebase Project

  1. Create a firebase project in the firebase console.( https://console.firebase.google.com)

2. Include two apps. one for iOS and one for Android

  iOS

  • Register an iOS app to Firebase using the app’s bundle id.

  • Add GoogleService-info to your project folder after downloading it.

  • Complete the remaining steps on the Firebase console.

Android

  • Get your Android app registered.

  • Download the google-services.json config file and place it in the android project’s app module.

Set up a database

To build a Cloud Firestore database, go to the left menu on the Firebase console and click Database.

Select database security rules; for our demonstration, we’ll use test mode, which will create a public database that anybody can view and write to.

Create Flutter project

1. Create a new project with the flutter create command.

flutter create firestore_database

2. Open the ios/Runner.xcworkspace folder. In the Runner folder, save the GoogleService-info.plist file.

Similarly, launch Android Studio and place the google-services.json file in the android project’s app module.

3. Open the pubspec.yaml file in your IDE or editor. Save the file after adding cloud firestore as a dependent.

dependencies:
  flutter:
   sdk: flutter
  cloud_firestore: ^0.11.0+2

Run the following command from the project directory.

flutter pub get

SetUp

1. Import dependency for firestore.

import 'package:cloud_firestore/cloud_firestore.dart';

2. To interact with a database, create a database Reference object

final databaseReference = Firestore.instance;

Make a screen with CRUD operation buttons.

Make a Collection and Insert a Document

Data in Fire store is stored in documents. These documents are housed in collections. In our scenario, we will build a collection called “clothing,” add documents to it, and then add data to the documents.

1. When you click the “Create Record” button, the createRecord() method is called.

InkWell(
                 onTap: () {
                   createRecord();
                 },
                 child: Container(
                   padding: EdgeInsets.all(10),
                  alignment:Alignment.center
                   decoration: BoxDecoration(
                     color: Colors.blue,
                     borderRadius: BorderRadius.circular(5),
                   ),
                   child: Text(
                     "Create Record",
                     style: TextStyle(color: Colors.white),
                   ),
                 ),
               )

2.We create two demo records in the database using createRecord().

   void createRecord() async {
  await databaseReference.collection("clothing")
      .document("1")
      .setData({
        'title': 'Shirt',
        'description': 'Amazing Shirt'
      });

  DocumentReference ref = await databaseReference.collection("clothing")
      .add({
        'title': 'T-Shirt',
        'description': 'T-Shirt'
      });
  print(ref.documentID);
}

when using the collection(“clothing”) document(“1”) A document is created in the collection “clothing,” and data is added to it using setData(). when using collection(“clothing “)

add() has done the same thing, however, the document name is chosen at random by firestore because we haven’t supplied one

Retrieve and Show a Data

To access the data, we must obtain all documents or a specific document from that collection. We must supply the document id in order to retrieve a specific document.

void getRecord() {
  databaseReference
      .collection("clothing")
      .getDocuments()
      .then((QuerySnapshot snapshot) {
    snapshot.documents.forEach((f) => print('${f.data}}'));
  });
}

Update Document Data

void updateRecord() {
  try {
    databaseReference
        .collection('clothing')
        .document('1')
        .updateData({'description': 'Super Shirt'});
  } catch (e) {
    print(e.toString());
  }
}

It changes the title of document id 1 to ‘Super Shirt

Delete Document

void deleteRecord() {
    try {
      databaseReference.collection('clothing').document('1').delete();
    } catch (e) {
      print(e.toString());
    }
  }

2. It removes document 1 from the clothing collection.

Complete Code

import 'package:flutter/material.dart';

import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MediaQuery(
      data: new MediaQueryData(), child: new MaterialApp(home: new MyApp())));
}

class MyApp extends StatelessWidget {
  final databaseReference = Firestore.instance;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FireStore Demo'),
      ),
      body: Center(
          child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          SizedBox(
            height: 10,
          ),
          InkWell(
            onTap: () {
              createRecord();
            },
            child: Container(
              padding: EdgeInsets.all(10),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.circular(5),
              ),
              child: Text(
                "Create Record",
                style:
                    TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          InkWell(
            onTap: () {
              getRecord();
            },
            child: Container(
              padding: EdgeInsets.all(10),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.circular(5),
              ),
              child: Text(
                "View Record",
                style:
                    TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          InkWell(
            onTap: () {
              updateRecord();
            },
            child: Container(
              padding: EdgeInsets.all(10),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.circular(5),
              ),
              child: Text(
                "Update Record",
                style:
                    TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          InkWell(
            onTap: () {
              deleteRecord();
            },
            child: Container(
              padding: EdgeInsets.all(10),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.red,
                borderRadius: BorderRadius.circular(5),
              ),
              child: Text(
                "Delete Record",
                style:
                    TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
        ],
      )), //center
    );
  }

  void createRecord() async {
    await databaseReference
        .collection("clothing")
        .document("1")
        .setData({'title': 'Shirt', 'description': 'Amazing Shirts'});

    DocumentReference ref = await databaseReference
        .collection("clothing")
        .add({'title': 'T-Shirt', 'description': 'T-Shirt'});
    print(ref.documentID);
  }

  void getRecord() {
    databaseReference
        .collection("clothing")
        .getDocuments()
        .then((QuerySnapshot snapshot) {
      snapshot.documents.forEach((f) => print('${f.data}}'));
    });
  }

  void updateRecord() {
    try {
      databaseReference
          .collection('clothing')
          .document('1')
          .updateData({'description': 'Super Shirt'});
    } catch (e) {
      print(e.toString());
    }
  }

  void deleteRecord() {
    try {
      databaseReference.collection('clothing').document('1').delete();
    } catch (e) {
      print(e.toString());
    }
  }
}

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories