簡體   English   中英

如何在streambuilder中運行一次異步function

[英]How to run async function once in streambuilder

我有一個流構建器,我試圖調用一個 function 來更新我的應用程序的讀取狀態

void readMessage() async {
int num = 0;
final query = await FirebaseFirestore.instance
    .collection('chats')
    .doc(chatroomId(FirebaseAuth.instance.currentUser!.uid, widget.uid))
    .collection('messages')
    .where('uid', isEqualTo: widget.uid)
    .where('read', isEqualTo: false)
    .get();

query.docs.forEach((doc) {
  doc.reference.update({'read': true});
});

num = query.docs.length;

await FirebaseFirestore.instance
    .collection('users')
    .doc(FirebaseAuth.instance.currentUser!.uid)
    .update(
  {"messagesNotification": FieldValue.increment(-num)},
);
}

在我的streambuilder中我正在嘗試

return Container(
      child: StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection('chats')
            .doc(chatRoom)
            .collection('messages')
            .orderBy('createdAt', descending: true)
            .snapshots(),
        builder: (context,
            AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
          readMessage();

問題是它似乎運行了兩次,所以如果他們有 3 條未讀消息,它會將消息計數器減少 3,然后再減少 3。 我也不確定這是否是它的工作原理,但我是否相信如果 stream 中出現新消息,它將每次運行該方法,以便在 stream 打開時將傳入消息標記為已讀?

StreamBuilder小部件通過 stream 的每次更改重建 ui,因此您需要使用條件語句包裝readMessage()以決定是否運行此 function

您可以創建一個 boolean 來檢查是否調用了 function

bool functionCalled = false;

檢查是否調用了 function,如果沒有,請執行邏輯並在其中將其設置為 true。 下一個調用不會跳轉到 if 中。

if(!functionCalled){
functionCalled = true;
int num = 0;
final query....
}

暫無
暫無

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

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