尝试从Firestore获取数据时出错

时间:2020-04-12 17:29:28

标签: firebase flutter dart google-cloud-firestore firebase-authentication

当我尝试使用此代码从Firestore检索数据时。

     <script>
    function ver(){

    var eje=document.getElementById('zip_code').value;
    var che=document.getElementById('lugar').value;

    var cheje = che.toLowerCase();

    if( (eje == 11385 )||(cheje=="ridgewood" ) || (cheje=="glendale") || (cheje=="flushing")){
    window.location.assign("c:/users/lui/desktop/fluidimaging.html")
    }    

    else{ alert("you did not enter a city or a zip code"); }
    }




    </script>


    <HTML> 




    <form>      

    <legend>Please Enter Your City or Zip Code</legend>           <label for ="shippingName">City: 
    </label>          <input type = "text" name = "Name" pattern="[A-Za-z]+" id="lugar" <br/>


      <label for = "billingzip">Zip code:</label>         <input type = "text" name = "zip" id = 
     "zip_code" pattern = "[0-9]{5}"  required><br/> </form>

      <input type = "submit" onclick="ver()" class="submit" value = "Verify"/>  

我收到此错误

Future<String> getUserType() async {
        await (Firestore.instance
            .collection('users')
            .document(getUserUID().toString())
            .get()
            .then((DocumentSnapshot ds) {
          return ds['type'];
        }));
      }

我也尝试过:

 NoSuchMethodError: The method '[]' was called on null.
 I/flutter (15824): Receiver: null
 I/flutter (15824): Tried calling: []("type")

检索用户uid的代码为:

return ds.data['type'];

但是我不认为这是问题所在,也许在ds中什么也没有。

2 个答案:

答案 0 :(得分:1)

您需要先检索userID,然后在文档检索中使用它:

Future<String> getUserType() async {
String userID = (await _firebaseAuth.currentUser()).uid;
        await (Firestore.instance
            .collection('users')
            .document(userID)
            .get()
            .then((DocumentSnapshot ds) {
          return ds['type'];
        }));
      }

在您的代码中:

Future<String> getUserUID() async {
    return (await _firebaseAuth.currentUser()).uid;
  }

getUserUID()返回一个Future,但是当您执行.document(getUserUID().toString())时,您不会得到该Future的结果。

检查以下内容:

https://dart.dev/codelabs/async-await

答案 1 :(得分:0)

您的getUserUID()方法返回的是Future String而不是常规String。因此您不能通过提供该字符串直接获取文档。这是我实现此类功能的常用方式。

Future<String> getUserType() async {
 getUserUID().then((currentUser) {
  if (currentUser != null) {
    await (Firestore.instance
        .collection('users')
        .document(currentUser)
        .get()
        .then((DocumentSnapshot ds) {
      return ds['type'];
    }));
   }
   }
  }