firebase - 如何在Firebase中的文档中添加多个字段?

标签 firebase flutter dart google-cloud-firestore

我想将某些设备的设备 token 保存在单个文档的不同字段中。
这是我的代码,


StreamBuilder(
              stream: stream,
              builder: (BuildContext context,
                  AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
                if (snapshots.connectionState == ConnectionState.active &&
                    snapshots.hasData) {
                  return Expanded(
                    child: ListView.builder(
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      itemCount: snapshots.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        DocumentSnapshot doc = snapshots.data[index];
                        Map location = doc.data;
                        String fieldname = 'f$index';

                        var dtoken = location['deviceToken'];

                       
                         

                          _firestore.collection('deviceTokens').add({
                            fieldname: dtoken,
                          });
                       
                     
              

                       
                        return Text(
                          "xyz",
                        );
                      },
                    ),
                  );
                } else {
                  return Center(child: CircularProgressIndicator());
                }
              },
            ),

我想在一个文档中存储多个deviceTokens。
更清楚地说,
运行此代码时,我只希望在数据库中创建一个文档,该文档在多个字段中具有设备 token ,例如,
在一个文件中
f1:“第一设备 token ”,
f2:“第二设备 token ”,
fn:“第n个设备 token ”
但是此代码创建了许多具有不同设备 token 的文档(每个文档1个字段)。
请帮忙
更新的代码
StreamBuilder(
              stream: stream,
              builder: (BuildContext context,
                  AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
                if (snapshots.connectionState == ConnectionState.active &&
                    snapshots.hasData) {
                  return Expanded(
                    child: ListView.builder(
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      itemCount: snapshots.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        var docid;

                        if (index == 0) {
                         _firestore
                              .collection('devicetokens')
                              .add({}).then((value) => docid = value);
                        }
                        DocumentSnapshot doc = snapshots.data[index];
                        Map location = doc.data;
                        String fieldname = 'f$index';


                        var dtoken = location['deviceToken'];

                        DocumentReference docss =
                            _firestore.collection("devicetokens").document(docid);
                        docss.setData({
                          fieldname: dtoken,
                        });
                        
                       

                       
                        return Text(
                          "xyz",
                        );
                      },
                    ),
                  );
                } else {
                  return Center(child: CircularProgressIndicator());
                }
              },
            ),

最佳答案

替换为:

_firestore.collection('deviceTokens').add({
  fieldname: dtoken,
});
用这样的东西:
  DocumentReference doc = _firestore.collection(deviceTokens).document();
  doc.setData({
    "f1" : "1st device token",
    "f2" : "2nd device token",
    "fn" :"nth device token",
  });


编辑:这是一种方法。使用.document()方法同步获取docid。
不要使用.collection.add()来获取docID,因为它是异步的,这意味着在将来的解析之前它将一直为null(直到服务器返回docID)。您需要已经具有docID才能使用setData对其进行写入。
这应该工作。或者至少使您在解决方案的道路上步入正轨。
StreamBuilder(
              stream: stream,
              builder: (BuildContext context,
                  AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
                if (snapshots.connectionState == ConnectionState.active &&
                    snapshots.hasData) {

                    //This gets you a doc ID synchronously
                    DocumentReference docid = _firestore.collection(deviceTokens).document();

                  return Expanded(
                    child: ListView.builder(
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      itemCount: snapshots.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        

                        DocumentSnapshot doc = snapshots.data[index];
                        Map location = doc.data;
                        String fieldname = 'f$index';


                        var dtoken = location['deviceToken'];    

                        _firestore.collection("devicetokens")
                        .document(docid.documentID)
                        .setData({
                          fieldname: dtoken,
                        });
                        
                       

                       
                        return Text(
                          "xyz",
                        );
                      },
                    ),
                  );
                } else {
                  return Center(child: CircularProgressIndicator());
                }
              },
            ),

关于firebase - 如何在Firebase中的文档中添加多个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63281712/

相关文章:

ios - 如何知道 FirebaseApp.configure() 何时完成?

javascript - 如何仅在将子项添加到数据库时才触发云功能?

macos - 如何发布一个用flutter编写的macos应用

flutter - 如何解决无限像素溢出的底部?

java - Firebase 的 limitToLast() 方法未按预期工作

swift - 使用唯一键 + 自定义名称将数据保存在 Firebase 实时数据库中

dart - Flutter 生命周期暂停方法未被调用

dart - 没有方法 channel 的请求权限

当我停止播放带有功能的歌曲并更改导航栏索引时, flutter 音乐继续播放

dictionary - flutter/Dart : How to access a single entry in a map/object