I have question collection and some 'X' number of fields in that, but now I want to set an array of key value pairs in existing document of my firestore collection question for storing the data in my firestore the desired structure is shown below in image, I am not able to get how to create structure like this I want to fetch them and create data in firestore using flutter and dart,
so far I am able to set string fields like this but not array of them,
Future<void> setAnswer() async {
String ans = ans_Controller.text;
FirebaseFirestore db = FirebaseFirestore.instance;
await db.runTransaction((transaction) async {
DocumentReference qRef =
db.collection('question').doc(widget.question.id);
await transaction.set(
qRef,
{
'content': ans,
'timestamp': DateTime.now().toString(),
'username': _currentUser.displayName,
},
SetOptions(merge: true));
});
}
and also every array element must have same key but different values, like a hashmap
any help is appreciated,
thank you
I think you're looking for the array-union
operation . To add an element to the answer
array if it doesn't exist in there yet, do:
documentRef.updateData({'answer': FieldValue.arrayUnion([{
'content': ans,
'timestamp': DateTime.now().toString(),
'username': _currentUser.displayName,
}])});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.