1

i have something like this in firebase

songList {
songName1: "HelloWorld",
songName2: "AnotherSong",
songName3: "andTheLastOne"
}

i am trying to delete key value songName2 but my code is not given error and not working.

Future<Either<ServerError, bool>> deleteNewFollow(String id) async {
  try {
    // Note you can use this format but i refer the other option...
    // await ref.update({
    //   'reqfellowers': FieldValue.arrayRemove([{}.remove(id)])
    // });
    await firestore
        .collection("users")
        .doc(auth.currentUser!.uid)
        .update({'reqfellowers.$id': FieldValue.delete()});
    await firestore
        .collection("users")
        .doc(id)
        .update({'sentRequest.${auth.currentUser!.uid}': FieldValue.delete()});
    return right(true);
  } catch (e) {
    print("=====> $e");
    return left(ServerError(e.toString()));
  }
}

here is the image if maps

enter image description here

Gbenga B Ayannuga
  • 2,407
  • 3
  • 17
  • 38

1 Answers1

0

FieldValue.delete() only works when you know the entire contents of the array item to delete. It does not work with indexes, nor does it work with child values of array items. What you will have to do instead is read the document, modify the array in memory, then write the modified array back to the document. You can refer to the official Firestore documentation for guidance.
There are more examples here To use the value of variables you can try and do like this:

var data = {}; data[fileName] = FieldValue.delete();  
 Firestore.instance.collection("collectionReference").document(userName).updateData(data)

Here are a few similar examples you can refer to and update your code accordingly:

Vaidehi Jamankar
  • 1,232
  • 1
  • 2
  • 10