0

I have a StreamBuilder to get snapShot from my FB backend as an list. But I am trying to remove the first element from that list How can I do that?

code:

StreamBuilder<DocumentSnapshot?>(
        stream: FirebaseFirestore.instance
            .collection("users")
            .doc(userUid)
            .snapshots(),
        builder: (context, snapshot) {
          //SnapShot
          var rooms = snapshot.data?['room'];
          List<dynamic> room = rooms;
          return...

         //Action to remove 0
       ElevatedButton(
                    onPressed: () async => {
                      //Remove the first string in this array
                      room.removeAt(0)},
                   
                    child: const Text('Remove first element from array'),
                  ),

Error: type 'Null' is not a subtype of type 'List<dynamic>'

Img: enter image description here

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
It'sPhil
  • 61
  • 1
  • 2
  • 11

1 Answers1

1

Unfortunately, firebase doesn't support deleting by index.

The preferred approach would be:

Create a new subcollection room and there you add documents which were primarily array elements.

Then you could delete like so:

db.collection('users')
.doc(currentUser.uid)
.collection('room')
.doc(<room1-docId>) //  To delte room 1
.delete()

Note: Error Null is not subtype of type List<dynamic> is caused by

List<dynamic> room = rooms; // rooms are possibly Null , because of which you are getting the error.
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88