簡體   English   中英

循環通過 Flutter 中集合中的 Firestore 文檔時的 Null 值

[英]Null value when looping through Firestore documents in a collection in Flutter

我有以下 function 來循環瀏覽我在 Firestore 集合中擁有的文檔及其字段,並在控制台中將它們顯示為 map:

documentsLoopFromFirestore() {
    FirebaseFirestore.instance
      .collection('myCollection')
      .get()
      .then((idkWhatGoesHereButICantRemoveIt) {
        idkWhatGoesHereButICantRemoveIt.docs.forEach((result) {
      print(result.data());
    });
  });
}

當我在按鈕中調用documentsLoopFromFirestore()時:

ElevatedButton(
 onPressed: () {
   print(documentsLoopFromFirestore());
 }, 

我在控制台中得到以下結果:

I/flutter (29803): null
I/flutter (29803): {lastName: smith, name: peter}
I/flutter (29803): {lastName: doe, name: john}

它成功地在該 Firestore 集合中打印了我的文檔的值,但在此之前,它會拋出不允許我將此null添加到另一個集合中的 null,這是我的目標。

如果我將asyncawait添加到 function:

documentsLoopFromFirestore() async {
    await FirebaseFirestore.instance
      .collection('myCollection')
      .get()
      .then((idkWhatGoesHereButICantRemoveIt) {
        idkWhatGoesHereButICantRemoveIt.docs.forEach((result) {
      print(result.data());
    });
  });
}

然后我得到:

I/flutter (29803): Instance of 'Future<dynamic>'
I/flutter (29803): {lastName: smith, name: peter}
I/flutter (29803): {lastName: doe, name: john}

似乎在執行第一個循環時會拋出null 有誰知道我怎樣才能擺脫這個null

更改此打印(documentsLoopFromFirestore()); 到文檔LoopFromFirestore(); 在 ElevatedButton 中

您看到帶有第一個代碼和Instance od Future<dynamic>null的原因是您首先打印出 function 和結果。

在第一種情況下,function 不會返回任何內容,因此您會看到null ,在第二種情況下,function 是未來,您只需打印它就是未來。

為了避免刪除第一個打印或以 function 中所需格式返回值。

暫無
暫無

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

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