How to delete element from List from Firebase and in List with Dismissible?

592 views Asked by At

In my Flutter application I get the following error message on my Simulator Screen (iOS and Android):

A dismissed Dismissible widget is still part of the tree. Make sure to implement the onDismissed handler and to immediately remove the Dismissible widget from the application once that handler has fired.

I use the following code to delete/dismiss an element from my list:

return Dismissible(
        child: AnimalCard(
          animalList[index],
        ),
        key: Key(item[index]),
        background: Container(color: Colors.red[600]),
        onDismissed: (direction) {
          print("documents Animal:");
          print(documents[index]["Animal"]);
          removeAnimalUserFromFirebase(_user, documents[index]);
        },
      );

In my Logcat I get the following errors from the second "print-call":

The following StateError was thrown while notifying listeners for AnimationController: Bad state: field does not exist within the DocumentSnapshotPlatform

The dismissed element is never deleted in the Firebase database. In the application it is deleted until the page is refreshed.

The list is defined this way:

var animalList = <Animal>[];
  documents.forEach((d) {
    animalList.add(Animal(
       d['animal']['Name'],
       d['animal']['number']));
  });

The element which should be deleted is a document from a collection. The Firebase User-ID is the collection and the number of the animal (selected list element) is the document.

How can I solve this?

2

There are 2 answers

0
Abhijith A On

The problem might be that you are using index values as key. Instead of using index value try using key: UniqueKey(). Refer this for more details

And also provide the definition code of method removeAnimalUserFromFirebase(_user, documents[index]);

Hope this helps.

0
Huzaifa Khan On

void deleteListItem(String documentId, int index) async { // Get the document reference from the collection DocumentReference documentReference = FirebaseFirestore.instance.collection('collection_name').doc(documentId);

// Retrieve the document containing the List DocumentSnapshot documentSnapshot = await documentReference.get();

// Get the List from the document List list = documentSnapshot.data()!['list'];

// Remove the element from the List list.removeAt(index);

// Update the document in Firebase Cloud Firestore with the modified List await documentReference.update({'list': list}); }

ListView.builder(

itemCount: list.length, itemBuilder: (BuildContext context, int index) { return Dismissible( key: Key(list[index]), onDismissed: (direction) { deleteListItem(documentId, index); }, child: ListTile( title: Text(list[index]), ), ); }, );