MaxS
MaxS

Reputation: 153

Flutter & Firebase: Remove Item(Map) from Array in firebase

I'm currently struggling to remove a map item from a list in firebase. E.g. I want to remove item "0" from the list (completely).

enter image description here

I add the single array items in another place via FieldValue.arrayUnion with the updateData Method. This works perfectly fine. In another place in my I then want to have the possibility to remove the item from a list. I load the data via StreamBuilder and display ListTiles via ListView.builder. Now there I tried to replace arrayUnion by arrayRemove, but it doesn't work and I can't figure out why. Here's my code:

onPressed: () async {
  try {
    await Firestore.instance
        .collection('users')
        .document(futSnap.data.uid)
        .collection('trainings')
        .document(widget.trainingID)
        .updateData(
      {
        'trainingTitle': widget.trainingTitle,
        'trainingID': widget.trainingID,
        'trainingDate': widget.trainingDate,
        'category': widget.trainingCategory,
        'trainingExercises':
            FieldValue.arrayRemove(
          [
            {
              'title': trainingExercises[i]
                  ['title'],
              'description':
                  trainingExercises[i]
                      ['description'],
              'imageURL': trainingExercises[i]
                  ['imageUrl'],
              'repetitions':
                  trainingExercises[i]
                      ['repetitions'],
            },
          ],
        )
      },
    );
  } catch (e) {
    print(e);
  }
},

I don't receive any error or something.. Still a beginner to flutter and programming, so help would be highly appreciated :)

Upvotes: 8

Views: 4338

Answers (4)

Rajan Bhatia
Rajan Bhatia

Reputation: 11

Remove specific object/map from array

void removeMapFromFirebase(String documentId, Map<String, dynamic> mapToRemove) {
  
       FirebaseFirestore.instance.collection('yourCollection')
      .doc(documentId)
      .update({
        'yourArrayField': FieldValue.arrayRemove([mapToRemove])
      });
}

So here need to send whole object inside array like this given below

[mapToRemove]

Upvotes: 0

Ran
Ran

Reputation: 33

List<ExpenseData> deleteExpenseData = [];
deleteExpenseData.add(spendingDetailMapList[documentIndex][documentId[documentIndex]][spending]);
expenseCR.doc(documentId[documentIndex]).update({"spending": FieldValue.arrayRemove([deleteExpenseData[0].toJson()],)});

I did this and It works.

Upvotes: 1

MaxS
MaxS

Reputation: 153

Thanks for your replies, in trying further, it seems that this actually works now:

onPressed: () async {
                              try {
                                await Firestore.instance
                                    .collection('users')
                                    .document(futSnap.data.uid)
                                    .collection('trainings')
                                    .document(widget.trainingID)
                                    .updateData(
                                  {
                                    'trainingExercises':
                                        FieldValue.arrayRemove(
                                      [trainingExercises[i]],
                                    )
                                  },
                                );
                              } catch (e) {
                                print(e);
                              }
                            },

But to be fair I don't understand completely why, because my understanding was as well as yours, that the information has to match the whole map..? I'm happy that it works, but it would be awesome to understand why :D

Upvotes: 5

Doug Stevenson
Doug Stevenson

Reputation: 317352

Firestore doesn't offer any way to deal with array contents by index. If you want to remove a map from an array, you must either know the entire contents of the array to move (the exact value of every field of the map) and remove it with FieldValue.arrayRemove(). If I had to guess, I'd say you are not actually providing all of the exact values, since we can't see the values of the variables you're working with.

If you don't have all the exact values, you will have to read the entire document, modify the array in memory, then write the array field back to the document.

Upvotes: 1

Related Questions