You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何查询Firebase中当前用户的非好友并在ListView展示?

实现Firestore非好友用户查询并展示在ListView

步骤1:获取当前用户的好友ID列表

先从当前用户的friends子集合中提取所有已添加的好友ID,后续用来排除这些用户:

Future<List<String>> getCurrentUserFriends(String currentUserId) async {
  final friendsSnapshot = await FirebaseFirestore.instance
      .collection('users')
      .doc(currentUserId)
      .collection('friends')
      .get();
  
  return friendsSnapshot.docs.map((doc) => doc.id).toList();
}

步骤2:查询非好友且非当前用户的用户列表

拿到好友ID列表后,在users集合中筛选符合条件的用户,需要排除两个范围:当前用户自己、已添加的好友:

Stream<List<Map<String, dynamic>>> getNonFriendUsers(String currentUserId) async* {
  final friendIds = await getCurrentUserFriends(currentUserId);
  // 加入当前用户ID,避免查询到自己
  final excludedIds = [...friendIds, currentUserId];

  final usersStream = FirebaseFirestore.instance
      .collection('users')
      // 通过whereNotIn排除已在好友列表和当前用户的ID
      .where('uid', whereNotIn: excludedIds)
      .snapshots();

  await for (final snapshot in usersStream) {
    yield snapshot.docs.map((doc) => doc.data()).toList();
  }
}

注意:Firestore的whereNotIn最多支持500个元素,如果好友数量可能超过这个限制,建议在用户文档中新增friendIds数组字段(添加好友时同步更新双方的该字段),既减少子集合查询次数,也能更高效地完成筛选。

步骤3:用ListView展示结果

通过StreamBuilder监听查询结果,实时更新ListView内容:

class FriendRecommendations extends StatelessWidget {
  final String currentUserId;

  const FriendRecommendations({super.key, required this.currentUserId});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<Map<String, dynamic>>>(
      stream: getNonFriendUsers(currentUserId),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot.hasError) {
          return Center(child: Text('加载失败: ${snapshot.error}'));
        }

        final nonFriendUsers = snapshot.data ?? [];

        if (nonFriendUsers.isEmpty) {
          return const Center(child: Text('暂无好友推荐'));
        }

        return ListView.builder(
          itemCount: nonFriendUsers.length,
          itemBuilder: (context, index) {
            final user = nonFriendUsers[index];
            return ListTile(
              leading: CircleAvatar(
                backgroundImage: NetworkImage(user['avatarUrl'] ?? ''),
              ),
              title: Text(user['username'] ?? '未知用户'),
              subtitle: Text(user['bio'] ?? ''),
              trailing: ElevatedButton(
                onPressed: () {
                  // 此处实现添加好友的逻辑
                },
                child: const Text('添加好友'),
              ),
            );
          },
        );
      },
    );
  }
}

补充说明

  • 确保users集合的每个文档都包含uid字段(与文档ID一致),才能保证筛选匹配的准确性。
  • 如果需要更复杂的推荐逻辑(比如基于共同好友、兴趣标签),可以在查询时添加额外的where条件,或者结合Firestore的全文搜索扩展实现。

内容的提问来源于stack exchange,提问作者Efren Pineda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:10:38