Flutter: Update specific index in list (Firestore)

一曲冷凌霜 提交于 2020-07-13 15:09:45

问题


How exactly do you update a specific value in a list based on it's index? For example, in the following list:

0 [
    {
      first_name: name0,
      last_name: lastName0,
    }
  ]
1 [
    {
      first_name: name1,
      last_name: lastName1,
    }
  ]          

How can I update only "lastName1"? At the moment, I'm using a bit of a hacky solution using ArrayUnion, which uses data comparison instead of the actual index (I load the values into a form, delete the original value and then re-add it again):

 // Retrieve data at index, load into form

// Remove that index from List 
await Firestore.instance.collection(col).document(doc).updateData({
  'people': FieldValue.arrayRemove([person])
});

// Make changes to data via form

// Save back to list
 await Firestore.instance.collection(col).document(doc).updateData({
  'people': FieldValue.arrayUnion([person])
});

Is there a function that will allow me to specify which specific index's data to update? Something like (but using a List, not Map):

 await Firestore.instance.collection(col).document(doc).updateData({
  'people.$index.lastName1': 'newName')
 });

回答1:


For all client languages and platforms, it's currently not possibly to issue a single command to update an array item by index. There is no special syntax for that. What you will need to do instead is read the document, modify the field array data in the way that you want, and update that field back to the document, in its entirety. You can do this in a transaction if you want the update to be atomic.

See also:

  • Is there any way to update a specific index from the array in Firestore
  • Firestore Update single item in an array field
  • How to update an array item in Firestore
  • How to update an "array of objects" with Firestore?


来源:https://stackoverflow.com/questions/59123464/flutter-update-specific-index-in-list-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!