Delete data from Firestore - Delete Collection and subcollections

Last updated Apr 23, 2020

Firestore is server less database offered by Google. It will store data in the form of Collections, Documents and fields.

We all are know how to store data with these Collections and Documents.

Most of the people don't know how to delete documents, collections and individual fields.

In this post we are going to delete Collections, Subcollections, Documents and individual fields from Firestore database.

 

Let's get Started 

Step 1: Create Flutter Project

Step 2: Create Data in the Firestore like below

Firestore Delete Collections

collections:news->
                    Document-> 
                                Fields as array()->news[
                                                            {
                                                                "title":"",
                                                                "desc":""
                                                            },
                                                            {
                                                                "title":"",
                                                                "desc":""
                                                            }
                                                        ]

 

Step 3: Update Main dart file with below code

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

import 'newsmodel.dart';

class NewsScreen extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("News"),),
        body: Card(
          child: StreamBuilder(
              stream: Firestore.instance
                  .collection('news').snapshots(),
              builder: (context, snapshot){

                    if (!snapshot.hasData) {
                    return Center(
                    child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation(Colors.teal)));
                    } else {

                      var array=snapshot.data.documents[0]['news'];
                      print(snapshot.data.documents[0].toString());
                     return ListView.builder(
                       scrollDirection: Axis.vertical,
                        padding: EdgeInsets.all(10.0),
                        itemBuilder: (context, index) {
                                  News news=News.fromJson(snapshot.data.documents[0]['news'][index]);
                                  return Dismissible(
                                    background: slideRightBackground(),
                                    secondaryBackground: slideLeftBackground(),
                                    confirmDismiss:(direction) async {
                                      if (direction == DismissDirection.endToStart) {
                                    final bool res = await showDialog(
                                        context: context,
                                        builder: (BuildContext context) {
                                          return AlertDialog(
                                            content: Text(
                                                "Are you sure you want to delete ?"),
                                            actions: [
                                              FlatButton(
                                                child: Text(
                                                  "Cancel",
                                                  style: TextStyle(color: Colors.black),
                                                ),
                                                onPressed: () {
                                                  Navigator.of(context).pop();
                                                },
                                              ),
                                              FlatButton(
                                                child: Text(
                                                  "Delete",
                                                  style: TextStyle(color: Colors.red),
                                                ),
                                                onPressed: () {
                                                
                                                },
                                              ),
                                            ],
                                          );
                                        });
                                    return res;
                                  } else {
                          // TODO: Navigate to edit page;
                          }
                      },
                                    key: Key('$index'),
                                    child:Container(
                                    margin: EdgeInsets.all(2),
                                    child: Card(
                                      elevation: .5,
                                      shape: OutlineInputBorder(),
                                      child: ListTile(

                                      title: Text(news.title,style: TextStyle(color: Colors.teal,fontSize: 15),),
                                      subtitle: Text(news.desc,style: TextStyle(color: Colors.grey,fontSize: 12,),maxLines: 2,)
                                ),
                                    ),
                                  ),);
                          },
                        itemCount: array.length,


                      );
                    }

          })/*Column(
            children: [
              ListTile(
                leading: CircleAvatar(
                  backgroundImage: NetworkImage(movie.imageUrl),
                ),
                title: Text(movie.title),
                subtitle: Text(movie.genre),
                trailing: Text(movie.year),
              )
            ],
          )*/,
        ),
      ),
    );
  }

  Widget slideLeftBackground() {
    return Container(
      color: Colors.red,
      child: Align(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Icon(
              Icons.delete,
              color: Colors.white,
            ),
            Text(
              " Delete",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w700,
              ),
              textAlign: TextAlign.right,
            ),
            SizedBox(
              width: 20,
            ),
          ],
        ),
        alignment: Alignment.centerRight,
      ),
    );
  }

  Widget slideRightBackground() {
    return Container(
      color: Colors.green,
      child: Align(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              width: 20,
            ),
            Icon(
              Icons.edit,
              color: Colors.white,
            ),
            Text(
              " Edit",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w700,
              ),
              textAlign: TextAlign.left,
            ),
          ],
        ),
        alignment: Alignment.centerLeft,
      ),
    );
  }
}

 

In the above code we are Fetching data from Firestore and display it on List with StreamBuilder widget.

Here we added Dismissible() widget to get SwipeLeft,SwipeRight events.

Dismissible(
    background: slideRightBackground(),
    secondaryBackground: slideLeftBackground(),
    confirmDismiss:(direction) async { },
    key: Key('$index'),
    child:Container(
    margin: EdgeInsets.all(2),
    child: Card(
      elevation: .5,
      shape: OutlineInputBorder(),
      child: ListTile(

      title: Text(news.title,style: TextStyle(color: Colors.teal,fontSize: 15),),
      subtitle: Text(news.desc,style: TextStyle(color: Colors.grey,fontSize: 12,),maxLines: 2,)
),
    ),
  ),)

 

Step 4: Now Add functionality to Delete Collections and Fields from FireStore data.

 

Delete Individual Fields from Collections

Add below code onPressed() function

onPressed: () {
      var list=  new List>();
      Map m=new Map();
      m.putIfAbsent("title", () => news.title);
      m.putIfAbsent("desc", () => news.desc);
      list.add(m);
  Firestore.instance.collection('news').document('jkR3jFrwztqzrr5OzPii').updateData({'news':FieldValue.arrayRemove(list) }).whenComplete((){
    print('Field Deleted');
  });

  Navigator.of(context).pop();
}

 

This will remove the Fields of array Item from news array.

Now the Data in database will be like below

Delete Fields Data

Now the news array is Empty. 

FieldValue.arrayRemove(list) did the login for remove the item from Array Filed.

Suppose if we want to delete individual filed then use FieldValue.delete()

 

How to Delete Document from database?

Lets use the below logic to delete complete document.

onPressed: () {
 
  Firestore.instance.collection('news').document(  snapshot.data.documents[0].documentID).delete();
  Navigator.of(context).pop();
},

 

In this Post we are using Single Document with Multiple Fields as Array data.

SwipeToDismiss

 

Swipe to Delete

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1861 Views