简体   繁体   English

如何从 Firestore 中的文档中获取字段值?

[英]How to get a field value from a Document in Firestore?

So, I have learned how to create and update documents in a firebase firestore cloud, however I am having trouble reading data.所以,我已经学会了如何在 firebase 火库云中创建和更新文档,但是我在读取数据时遇到了问题。 Attached is my code for finding the value of the 'photourl' field:附件是我查找“photourl”字段值的代码:

String photoy; 
Firestore.instance.collection('userdata').document('sepDGexTRuRkpx1WQYylDDmUI573')
.get().then((DocumentSnapshot ds){
          photoy=ds.data['photourl'];      
});

  setState(() {
              photourldisplay=photoy;
             });   

However, upon running my program, the photourldisplay value seems to not have changed and remains null upon running.但是,在运行我的程序时,photourldisplay 的值似乎没有改变,并且在运行时仍然是 null。 This means that something is askew with my code that retrieves this "photourl" field.这意味着我检索此“photourl”字段的代码有问题。 Can someone help me retrieve a field in a firebase document?有人可以帮我检索 firebase 文档中的字段吗? Firebase 文档 Firebase 安全规则

photoy does not contain the value you expect because Firestore queries are asynchronous. photoy不包含您期望的值,因为 Firestore 查询是异步的。 The get() returns immediately, and the callback is invoked some time later, after the query completes. get() 立即返回,并在查询完成后的一段时间后调用回调。 There is no guarantee how long a query might take.无法保证查询可能需要多长时间。 If you want to pass the value of photoy to something else, you will have to wait until the callback completes by making use of it only within that callback.如果您想将photoy的值传递给其他东西,您将不得不等到回调完成,仅在该回调中使用它。

Firestore.instance.collection('userdata').document('sepDGexTRuRkpx1WQYylDDmUI573')
.get().then((DocumentSnapshot ds){
    photoy=ds.data['photourl'];      

    setState(() {
        photourldisplay=photoy;
    });   
});

Your code is good you just have to await for the result:你的代码很好,你只需要等待结果:

void yourVoid () async {
    String photoy;
    await Firestore.instance.collection('userdata').document('sepDGexTRuRkpx1WQYylDDmUI573')
        .get().then((DocumentSnapshot ds){
      photoy=ds.data['photourl'];
    });

    setState(() {
      photourldisplay=photoy;
    });
  }

EDIT: as @Doug Stevenson said, there is two propers solutions:编辑:正如@Doug Stevenson 所说,有两种解决方案:

void yourVoid () async {


    DocumentSnapshot ds = await Firestore.instance.collection('userdata').document('sepDGexTRuRkpx1WQYylDDmUI573')
        .get();

    String photoy = ds.data['photourl'];

    setState(() {
      photourldisplay=photoy;
    });
  }

and:和:

Firestore.instance.collection('userdata').document('sepDGexTRuRkpx1WQYylDDmUI573')
.get().then((DocumentSnapshot ds){
    photoy=ds.data['photourl'];      

    setState(() {
        photourldisplay=photoy;
    });   
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM