Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update field in document on cloud firestore using Flutter?

I tried to update my firestore database field.

  Future<void> approveJob(String categoryId) {

comment line is updated on database. But I hard code uid. Is it possible to get uid without store?

   //return _db.collection('jobs').document('25FgSmfySbhEPe1z539T').updateData({'isApproved':true});


   return _db
        .collection('jobs')
        .where("categoryId", isEqualTo: categoryId)
        .getDocuments()
        .then((v) {
          try{
            v.documents[0].data.update('isApproved', (bool) => true,ifAbsent: ()=>true);

// No Errors. But not updating

         }catch(e){
            print(e);
          }
    });
  }
like image 462
BIS Tech Avatar asked Feb 02 '26 11:02

BIS Tech


2 Answers

===December 2020===

There are two methods for updating Firestore documents in Flutter:

  1. set() - Sets data on the document, overwriting any existing data. If the document does not yet exist, it will be created.
  2. update() - Updates data on the document. Data will be merged with any existing document data. If no document exists yet, the update will fail.

So, for updating the exact field in the existing document you can use

FirebaseFirestore.instance.collection('collection_name').doc('document_id').update({'field_name': 'Some new data'});
like image 79
awaik Avatar answered Feb 05 '26 04:02

awaik


  • To update a value in the document:

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('doc_id') 
        .update({'key' : 'value'}) // <-- Updated data
        .then((_) => print('Success'))
        .catchError((error) => print('Failed: $error'));
    
  • To update a nested value in the document.

    var collection = FirebaseFirestore.instance.collection('collection');
    collection 
        .doc('doc_id')
        .update({'key.foo.bar' : 'nested_value'}) // <-- Nested value
        .then((_) => print('Success'))
        .catchError((error) => print('Failed: $error'));
    
  • To add a new value to the existing document.

    var collection = FirebaseFirestore.instance.collection('collection');
    collection
        .doc('doc_id')
        .set(yourData, SetOptions(merge: true)); // <-- Set merge to true.
    
like image 20
CopsOnRoad Avatar answered Feb 05 '26 04:02

CopsOnRoad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!