Sunshine
Sunshine

Reputation: 334

Getting Firestore document ID when mapping Collection

I'm building a List View in Flutter using

          ...snapshot.data.docs.map((DocumentSnapshot document) {
            Map<String, dynamic> data =
                document.data() as Map<String, dynamic>;

but I'd like to delete a document from firebase when it's corresponding List Tile is pressed

I was thinking of using

              onTap: () async {
                await FirebaseFirestore.instance
                    .collection('User Data')
                    .doc('document_id')
                    .delete();
              },

to do so but I need the document_id how do I get the document ID when mapping ?

here is my full code

          ...snapshot.data.docs.map((DocumentSnapshot document) {
            Map<String, dynamic> data =
                document.data() as Map<String, dynamic>;
            return InkWell(
              onTap: () async {
                await FirebaseFirestore.instance
                    .collection('User Data')
                    .doc('document_id')
                    .delete();
              },
              child: HomeCard(

🙏

Upvotes: 1

Views: 554

Answers (1)

Mudassir
Mudassir

Reputation: 806

The DocumentSnapshot class has an id property.

         ...snapshot.data.docs.map((DocumentSnapshot document) {
            Map<String, dynamic> data =
                document.data() as Map<String, dynamic>;
            return InkWell(
              onTap: () async {
                await FirebaseFirestore.instance
                    .collection('User Data')
                    .doc(document.id)
                    .delete();
              },
              child: HomeCard(

You can check the docs on the Flutter api page.

Upvotes: 2

Related Questions