Home > Software engineering >  How to update field in firebase flutter?
How to update field in firebase flutter?

Time:01-17

I want to update my avatar in a shorter way

I use this way to update

[![](https://i.stack.imgur.com/aZj2j.png)](https://i.stack.imgur.com/aZj2j.png)

I don't know if there is a shorter way to update, thanks if anyone can help

CodePudding user response:

To update Firestore documents in Flutter you can use:

var collection = FirebaseFirestore.instance.collection('collection'); // <-- Here you use your collection name instead of 'collection'
collection 
    .doc('doc_id') // <-- Here you use your document id instead of 'doc_id'
    .update({'key' : 'value'}) // <-- Here you use your key name(your data store column name , previous used in firestore) instead of 'key' & use your image url nstead of 'value'
    .then((_) => print('Success')) // <-- Handle any success case 
    .catchError((error) => print('Failed: $error')); // <-- Handle any error case 

CodePudding user response:

Your code do need to be refactored and edited, I see that you're getting the whole collection and iterating over them all to get the id which equals the myID, this result to unnecessary internet data lost, unnecessary billed operation which is reading the collection and unnecessary client filtering work since Firestore can handle it on it's servers, instead, consider targeting the document with the myID, and call update() over it directly and let Firestore handles the searching/updating work:

await FirebaseFirestore.instance.collection("jobs").doc(myID).update({/*YOUR CONTENT*/});

This line can replace the the code you're using.

  • Related