如何在Flutter中通过Firestore判断数组含指定字符串并提示信息
解决Firestore数组包含检查的异步处理问题
你的代码核心问题有两个:
- Firestore的查询是异步操作,不能直接同步判断结果;
where()方法返回的是Query对象,不是布尔值,直接和true比较完全不成立。
针对「检查集合中是否存在含目标邮箱的文档」的解决方案
用FutureBuilder处理异步查询,根据返回的快照结果判断是否有匹配文档:
FutureBuilder<QuerySnapshot>( future: FirebaseFirestore.instance .collection('users') .where('requests', arrayContains: user.email) .get(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Text("加载中..."); } if (snapshot.hasError) { return const Text("查询出错,请稍后重试"); } // 若查询到至少一个文档,说明邮箱存在于某个用户的requests数组中 bool emailExists = snapshot.data!.docs.isNotEmpty; return Text(emailExists ? "邮箱已在请求列表中" : "邮箱未在请求列表中"); }, )
针对「检查单个指定文档的数组是否含目标邮箱」的解决方案
如果你的需求是检查某个特定文档(而非整个集合),直接获取该文档并判断数组内容:
FutureBuilder<DocumentSnapshot>( // 替换成你要检查的目标文档ID future: FirebaseFirestore.instance.collection('users').doc('target_doc_id').get(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Text("加载中..."); } if (snapshot.hasError) { return const Text("查询出错,请稍后重试"); } if (!snapshot.hasData || !snapshot.data!.exists) { return const Text("目标文档不存在"); } // 取出文档中的requests数组 List<dynamic>? requests = snapshot.data!.get('requests') as List<dynamic>?; bool emailExists = requests != null && requests.contains(user.email); return Text(emailExists ? "邮箱已在请求列表中" : "邮箱未在请求列表中"); }, )
内容的提问来源于stack exchange,提问作者Bart Stencil
相关产品推荐
相关产品推荐

