首页 > 解决方案 > 如何在 StreamBuilder 中添加 whereIn

问题描述

我目前遍历列表列表以获取对事件感兴趣的用户。我设置了它,initState但是在从文档中添加或删除 id 时Firestore,更改不会反映在 UI 中。我不想手动更新列表。有没有办法将此代码从移动initState到 a StreamBuilder

  @override
  void initState() {
    super.initState();
    final interestedUsers = widget.content.interested;

    var chunks = [];
    for (var i = 0; i < interestedUsers.length; i += 10) {
      chunks.add(interestedUsers.sublist(i,
          i + 10 > interestedUsers.length ? interestedUsers.length : i + 10));
    }

    for (var i = 0; i < chunks.length; i++) {
      final snapshot = FirebaseFirestore.instance
          .collection('users')
          .where('uid', whereIn: chunks[i])
          .snapshots();

      snapshot.forEach((element) {
        element.docs.forEach((element) {
          final userElement = UserModel.fromFirestore(element);
          setState(() {
            interested.add(userElement);
          });
        });
      });
    }
  }

标签: fluttergoogle-cloud-firestore

解决方案


你可以像这里这样写......这是一个处理加载和空状态的完整示例:

StreamBuilder(
          stream: _firestore
              .collection('users')
          .where('uid', whereIn: chunks[i])
          .snapshots(),
          builder:
              (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {

            //Shows loading indicator
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator( ),
              );
            }

            List<UserNotificationListTile> items = [];
            unredNotifications = [];

            List<QueryDocumentSnapshot> groups = snapshot.data.docs;

            for (QueryDocumentSnapshot g in groups) {
              UserNotification userNotification =
                  new UserNotification.fromSnapshot(g);
              items.add(
                UserNotificationListTile(
                  userNotification: userNotification,
                ),
              );
            }


            //Shows result when there is no data
            if (items.length == 0) {
              return Center(child: NotificationsEmpty());
            }

            return Column(
              children: [
                Expanded(
                  child: ListView(
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                    children: items.reversed.toList(),
                  ),
                ),
              ],
            );
          }),
    );

推荐阅读