0

I am using Firestore as a database in my Flutter app, and I am using a StreamBuilder to access the data. But, whenever I try to do a delete operation using a button press, Flutter always returns this error:

The following StateError was thrown building StreamBuilder<DocumentSnapshot<Object?>>(dirty, state:
_StreamBuilderBaseState<DocumentSnapshot<Object?>, AsyncSnapshot<DocumentSnapshot<Object?>>>#3bac1):
Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist

but then proceeds to delete the item. I am able to add, update and read all the items in the collection, but this error always appears whenever I try to delete them. How could I make the error stop appearing?

This is the widget where the error occurs (It's quite long, I know), but I have removed some parts because they weren't very applicable or useful in this issue.

StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
          stream: FirebaseFirestore.instance
              .collection('users')
              .doc(widget.uid)
              .collection('passwords')
              .doc(widget.password['appName'])
              .snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return const Center(
                child: CircularProgressIndicator(),
              );
            } else {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const SizedBox(),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(12, 12, 12, 0),
                      child: SizedBox.fromSize(
                        size: const Size.fromHeight(80),
                        child: Container(
                          decoration: BoxDecoration(
                              color: const Color(0xFF0C163F),
                              borderRadius: BorderRadius.circular(15)),
                          child: Row(
                            children: [
                              Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Padding(
                                    padding: EdgeInsets.fromLTRB(16, 14, 0, 0),
                                    child: Text(
                                      'Login:',
                                      style: TextStyle(color: Colors.white),
                                      textAlign: TextAlign.left,
                                    ),
                                  ),
                                  Padding(
                                    padding:
                                        const EdgeInsets.fromLTRB(18, 4, 0, 0),
                                    child: Text(
                                      snapshot.data!['login'],
                                      style: const TextStyle(
                                        color: Colors.white,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 16,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              const Spacer(),
                              Padding(
                                padding: const EdgeInsets.only(right: 12.0),
                                child: GestureDetector(
                                  child: const Icon(
                                    Icons.copy,
                                    color: Colors.white,
                                  ),
                                  onTap: () {
                                    Clipboard.setData(ClipboardData(
                                        text: 
                                      snapshot.data!['login'],));
                                  },
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(12, 12, 12, 0),
                      child: SizedBox.fromSize(
                        size: const Size.fromHeight(80),
                        child: Container(
                          decoration: BoxDecoration(
                              color: const Color(0xFF0C163F),
                              borderRadius: BorderRadius.circular(15)),
                          child: Row(
                            children: [
                              Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Padding(
                                    padding: EdgeInsets.fromLTRB(16, 14, 0, 0),
                                    child: Text('Password:',
                                        style: TextStyle(color: Colors.white)),
                                  ),
                                  FittedBox(
                                    fit: BoxFit.cover,
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(
                                          18, 4, 0, 0),
                                      child: Text(
                                        snapshot.data![‘password’]
                                        style: const TextStyle(
                                          color: Colors.white,
                                          fontWeight: FontWeight.bold,
                                          fontSize: 16,
                                        ),
                                      ),
                                    ),
                                  )
                                ],
                              ),
                              const Spacer(),
                              Padding(
                                padding: const EdgeInsets.only(right: 16.0),
                                child: GestureDetector(
                                  child: const Icon(
                                    Icons.remove_red_eye,
                                    color: Colors.white,
                                  ),
                                  onTap: () async {

                                  },
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.only(right: 12.0),
                                child: GestureDetector(
                                  child: const Icon(
                                    Icons.copy,
                                    color: Colors.white,
                                  ),
                                  onTap: () {
                                    Clipboard.setData(ClipboardData(
                                        text: 
                                      snapshot.data!['password']
                             
                                    ));
                                  },
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),
                      child: Row(
                        children: const [
                          Text('URLs:',
                              style: TextStyle(
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 15)),
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(5, 12, 5, 0),
                      child: ListView.builder(
                          scrollDirection: Axis.vertical,
                          shrinkWrap: true,
                          itemCount: snapshot.data!['url'].length,
                          itemBuilder: (context, index) {
                            List datalist = snapshot.data!['url'];

                            return Card(
                                child: ListTile(
                              title: Text(
                                datalist[index],
                                style: const TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 18),
                              ),
                            ));
                          }),
                    )
                    ,
                    const Spacer(),
                    Padding(
                        padding: const EdgeInsets.fromLTRB(12, 8, 12, 22),
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            minimumSize: const Size.fromHeight(50),
                            primary: const Color.fromARGB(255, 150, 13, 13),
                            shape: const RoundedRectangleBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10))),
                          ),
                          child: const Text('Delete Password'),
                          onPressed: () async {
                              await FirebaseFirestore.instance
                                  .collection('users')
                                  .doc(widget.uid)
                                  .collection('passwords')
                                  .doc(widget.password(appname))
                                  .delete();
                          },
                        ))
                  ],
                ),
              );
            }
          }),
    );
  }
}

This is the Firebase Console view:

enter image description here

bigman1234
  • 105
  • 2
  • 12
  • can you edit the question and show us what is there in widget? – Sathi Aiswarya Jun 23 '22 at 06:07
  • sure, ill do that – bigman1234 Jun 23 '22 at 17:14
  • I saw there is only one single document. is it possible to add more data inside the password collection? it looks like when you delete that one, and StreamBuilder will not find any data. – Frederic Chang Jun 23 '22 at 20:05
  • can you check this stackoverflow[link1](https://stackoverflow.com/a/68607904/18265638) &[link2](https://stackoverflow.com/a/63897960/18265638) once? – Sathi Aiswarya Jun 24 '22 at 06:49
  • @SathiAiswarya i tried to implement both answers in the links you attached, but im still getting the same error. the button on press still manages to delete the item from firestore, but the error still appears. – bigman1234 Jun 24 '22 at 10:10
  • @FredericChang, I thought of this before, but even after adding numerous documents to the collection, every time I try to delete a document, the error continuously appears. – bigman1234 Jun 24 '22 at 10:12
  • can you try these [github](https://github.com/projectsforchannel/firebase_crud) given in this [video](https://www.youtube.com/watch?v=PHf7NH2_gQs) and [link1](https://www.kindacode.com/article/flutter-firestore-database/) – Sathi Aiswarya Jun 27 '22 at 13:13
  • @SathiAiswarya i added this new delete function for the button to use, but the error appears again. – bigman1234 Jun 28 '22 at 11:51
  • @trashflutterdev I have provided an answer below to your question. Can you check if this helps. – Sathi Aiswarya Jul 03 '22 at 05:50

1 Answers1

0

Try deleting by manually passing those arguments. I think it is not possible to delete items within a builder by referencing widget arguments.To delete any document you must know it's ID or have a DocumentReference to it. For that you just need to know the userId

 FirebaseFirestore.instance
   .collection('users') 
   .doc(userId)
   .collection('favourites')
   .where('id', whereIn: [...])
   .get() 
   .then((snapshot) { 
     // ... 
   });

You may try deleting the snapshot using the following syntax

snapshot.docs[0].reference.delete(), where you can index into the object or snapshot.docs.get() where you can use the getter function.

You can refer link1 for Delete document by content of a field in Firestore and also may have a look at firestore doc

Sathi Aiswarya
  • 2,068
  • 2
  • 11