簡體   English   中英

如何創建和讀取Flutter中的鍵值對數組(map)用於Firestore中存儲數據

[英]How to create and read an array of key value pairs (map) in Flutter for storing data in Firestore

我有問題集合和一些“X”數量的字段,但現在我想在我的 firestore 集合問題的現有文檔中設置一組鍵值對,以便將數據存儲在我的 firestore 中所需的結構如下圖所示,我無法獲得如何創建這樣的結構我想獲取它們並使用 flutter 和 dart 在 firestore 中創建數據,

到目前為止,我可以像這樣設置字符串字段,但不能設置它們的數組,

 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));
      });
    }

並且每個數組元素必須具有相同的鍵但不同的值,例如 hashmap

在此處輸入圖像描述

任何幫助表示贊賞,

謝謝你

我認為您正在尋找array-union operation 要將一個元素添加到answer數組(如果它不存在),請執行以下操作:

documentRef.updateData({'answer': FieldValue.arrayUnion([{
  'content': ans,
  'timestamp': DateTime.now().toString(),
  'username': _currentUser.displayName,
}])});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM