Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update collection documents in firebase in flutter?

I want to update a document field and I've tried the following code but it doesn't update.

can anyone give me a solution, please?

My Code:

var snapshots = _firestore
        .collection('profile')
        .document(currentUserID)
        .collection('posts')
        .snapshots();

    await snapshots.forEach((snapshot) async {
      List<DocumentSnapshot> documents = snapshot.documents;

      for (var document in documents) {
        await document.data.update(
          'writer',
          (name) {
            name = this.name;
            return name;
          },
        );
        print(document.data['writer']);
       //it prints the updated data here but when i look to firebase database 
       //nothing updates !
      }
    });
like image 771
the coder Avatar asked Dec 07 '22 11:12

the coder


2 Answers

For cases like this, I always recommend following the exact types in the documentation, to see what options are available. For example, a DocumentSnapshot object's data property is a Map<String, dynamic>. To when you call update() on that, you're just updating an in-memory representation of the document, and not actually updating the data in the database.

To update the document in the database, you need to call the DocumentReference.updateData method. And to get from the DocumentSnapshot to a DocumentReference, you call the DocumentSnapshot.reference property.

So something like:

document.reference.updateData(<String, dynamic>{
    name: this.name
});

Unrelated to this, your code looks a bit non-idiomatic. I'd recommend using getDocuments instead of snapshots(), as the latter will likely result in an endless loop.

var snapshots = _firestore
        .collection('profile')
        .document(currentUserID)
        .collection('posts')
        .getDocuments();

await snapshots.forEach((document) async {
  document.reference.updateData(<String, dynamic>{
    name: this.name
  });
})

The difference here is that getDocuments() reads the data once, and returns it, while snapshots() will start observing the documents, and pass them to us whenever there's a change (including when you update the name).

like image 134
Frank van Puffelen Avatar answered Jan 12 '23 01:01

Frank van Puffelen


Update 2021:

Lot of things have changed in the API, for example, Firestore is replaced by FirebaseFirestore, doc is in, etc.

  • Update a document

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('some_id') // <-- Doc ID where data should be updated.
        .update({'key' : 'value'}) // <-- Updated data
        .then((_) => print('Updated'))
        .catchError((error) => print('Update failed: $error'));
    
  • Update nested value in a document:

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('some_id') // <-- Doc ID where data should be updated.
        .update({'key.foo.bar' : 'nested_value'}) // <-- Nested value
        .then((_) => print('Updated'))
        .catchError((error) => print('Update failed: $error'));
    
like image 36
CopsOnRoad Avatar answered Jan 11 '23 23:01

CopsOnRoad